ํ์ฑํ ์ฌ๋ถ๋ฅผ ํํํ๊ฑฐ๋ ํน์ ์คํ์ผ์ ์ก์์ค ๋ ์ ์ฉํ๋ค.
import styled, { css } from "styled-components";
import { useBoolean } from "usehooks-ts";
type ButtonProps = {
active: boolean,
};
// ์ด๋ ๊ฒ ํด๋ ๋๊ณ
function background(props: ButtonProps) {
return props.active ? "#00F" : "#FFF";
}
// ๋ด๋ถ์ ์จ๋ ๋๋ค.(์ด๋ฏธ ํ์
์ด ์ง์ ๋์ด ์์ผ๋ฏ๋ก ๋ํด์ค ํ์์์)
const Button =
styled.button <
ButtonProps >
`
background: #FFF;
color: #000;
border: 1px solid ${(props) => (props.active ? "#F00" : "#888")};
${(props) =>
props.active &&
css`
background: #f00;
color: #fff;
`}
`;
export default function Switch() {
const { value: active, toggle } = useBoolean(false);
return (
<Button type="button" onClick={toggle} active={active}>
On/Off
</Button>
);
}
props.active && css์์ css ๋ ์จ๋ ๋๊ณ ์์จ๋ ๋๋ค. ํ์
ํ์ฅ์ ๋์์ ๋ฐ๊ธฐ์ํด ์ฌ์ฉํ ๋ฟ์ด๋ค.
input ์ปดํฌ๋ํธ์ ๋ชจ๋ ํ๋กํผํฐ๊ฐ DOM ๋
ธ๋์ ์ ๋ฌ๋๋ค.
์ฌ๊ธฐ์ inputColor prop์ DOM์ ํตํ์ง ์์ง๋ง type๊ณผ defaultValue๋ DOM์ ํตํ๋ค. ๋นํ์ค ์์ฑ์ ์๋์ผ๋ก ํํฐ๋ง๋๋ ๊ฒ์ด๋ค.
const Input = styled.input`
padding: 0.5em;
margin: 0.5em;
color: ${(props) => props.inputColor || "palevioletred"};
background: papayawhip;
border: none;
border-radius: 3px;
`;
render(
<div>
<Input defaultValue="@probablyup" type="text" />
<Input defaultValue="@geelen" type="text" inputColor="rebeccapurple" />
</div>
);
attrs๋ฅผ ์ฌ์ฉํ๋ฉด ์์ฑ์ ๋ํ๋ผ ์ ์๋ค. ๋ฒํผ์์ ๋๊ฒ ์์ฃผ ์ฐ์ธ๋ค.
import styled from "styled-components";
// type ์์ฑ์ ์ ๋ฌ ๋ฐ์๋ค.
const Button = styled.button.attrs({
type: "button",
})`
border: 1px solid #888;
background: transparent;
cursor: pointer;
`;
export default Button;
const Input = styled.input.attrs((props) => ({
// ์ ์ ์ธ props๋ฅผ ์ ์ํ ์๋ ์๊ณ
type: "text",
// ๋์ ์ธ props๋ฅผ ์ ์ํ ์๋ ์๋ค.
size: props.size || "1em",
}))`
color: palevioletred;
font-size: 1em;
border: 2px solid palevioletred;
border-radius: 3px;
/* ์ฌ๊ธฐ์์ ๋์ ์ผ๋ก ๊ณ์ฐ๋ ํ๋กญ์ ์ฌ์ฉํ๋ค */
margin: ${(props) => props.size};
padding: ${(props) => props.size};
`;
render(
<div>
<Input placeholder="A small text input" />
<br />
<Input placeholder="A bigger text input" size="2em" />
</div>
);