5. props์ attrs
1. Props
์์ฑ์ ๋ฐ์์ ์ฐ๊ณ ์ถ์ ๋ ์ ์ฉ
๋์์ด ๋จ์ํ ์์์ผ ๊ฒฝ์ฐ, styled-components๋ HTML ์์ฑ์ ํตํด DOM์ผ๋ก ์ ๋ฌ ์ฌ์ฉ์ ์ง์ React ์ปดํฌ๋ํธ์ธ ๊ฒฝ์ฐ, ์คํ์ผ ์ปดํฌ๋ํธ๋ ๋ชจ๋ props๋ฅผ ํต๊ณผํจ ํ ํ๋ฆฟ ๋ฆฌํฐ๋ด์ ์ด์ฉํด์ ์กฐ๊ฑด๋ถ ์คํ์ผ ๋ฑ์ ํํ
ํ์ฑํ ์ฌ๋ถ ํํ
ํน์ ์คํ์ผ์ ์ก์์ฃผ๊ณ ์ถ์ ๋
์กฐ๊ฑด๋ถ ์คํ์ผ๋ง ๊ฐ๋ฅ
์ฌ์ฉ ๋ฐฉ๋ฒ
import { useBoolean } from 'usehooks-ts';
import styled, { css } from 'styled-components';
type ParagraphProps = {
active?: boolean;
}
const Paragraph = styled.p<ParagraphProps>`
color: ${(props) => (props.active ? '#F00' : '#888')};
${(props) => props.active && css`
font-weight: bold;
`}
`;
export default function Greeting() {
const { value: active, toggle } = useBoolean(false);
return (
<div>
<Paragraph>Inactive</Paragraph>
<Paragraph active>Active</Paragraph>
<Paragraph active={active}>
Hello, world
{' '}
<button type="button" onClick={toggle}>
Toggle
</button>
</Paragraph>
</div>
);
}
๐ก styled-components ์ { css } ๋ฅผ ํ์ฉํ๋ฉด, ๋จ์ ๋ฌธ์์ด์ด ์๋ CSS ์ฒ๋ผ ์ฌ์ฉํ ์ ์์
๐ก <ParagraphProps>
ํ์
์ ์ฌ์ฉํ์ง ์์ผ๋ ค๋ฉด <{ active: boolean }>
์ ํํ๋ก ์ง์ ์ ๋ ๊ฒ๋ ๊ฐ๋ฅ
โ๏ธ ์กฐ๊ฐ๊ธ
์ props๋ฅผ ์ด์ฉํ ๋
${(props) => props.active && css}
์ ๋ฐฉ์์ผ๋ก ์ ๋์ง ๋ชฐ๋๋๋ฐcss
๋ฅผ ์ ์ธํ๊ณ ์์ฑํด๋ณด๋ ๋ถํธํจ์ ์๊ฒ ๋์๋ค. ์คํ์ผ ์ฝ๋๋ฅผ ๋ฌธ์์ด๋ก ์ธ์ํด์ CSS๋ฅผ ์์ฑํ๊ธฐ ์ด๋ ค์ ๋ค. ์ ๋ชจ๋ฅด๋ฉด์ ์๋ ๊ทธ๋ฐ๊ฐ๋ณด๋ค ํ๊ณ ์ผ๋styled
๋ฅผ ์ฌ์ฉํ๋ ์ด์ ์ ๋ํด์๋ ์๊ฒ ๋๊ณ ,css
์ ์กด์ฌ ์ด์ ๋ ์๊ฒ ๋์ด ์ฆ๊ฒ๋ค.
2. attrs
Attaching additional props .attrs
๊ธฐ๋ณธ ์์ฑ์ ์ถ๊ฐํ ์ ์์ ๋ถํ์ํ๊ฒ ๋ฐ๋ณต๋๋ ์์ฑ์ ์ฒ๋ฆฌํ ๋ ์ ์ฉ
<button>
๋ฑ์ ๋ง๋ค ๋ ์ ๊ทน ํ์ฉtype="button"
๋ฑ์ ๋ฌด์กฐ๊ฑด ์จ์ผ ํ๋๋ฐ, ์ ์ฐ๋ฉด ์ค๋ฅ๊ฐ ๋ฐ์styled.button.attrs({ type: 'button' })
ํํ๋ก ์์ฑ
.attrs
์คํ์ผ ์ปดํฌ๋ํธ์ ์ผ๋ถ props๋ฅผ ์ฐ๊ฒฐํ๋ ์ฐ๊ฒฐ ๊ฐ๋ฅํ ๋ฉ์๋ ์ฒซ ๋ฒ์งธ์ด์ ์ ์ผํ ์ธ์๋ ์ปดํฌ๋ํธ์ ๋๋จธ์ง props์ ๋ณํฉ๋ ๊ฐ์ฒด
๊ฐ ๋ํผ๊ฐ .attrs
์ ์ค์ฒฉ ์ฌ์ฉ์ ์ฌ์ ์(override) ํ ์ ์์
์คํ์ผ์ํธ์์ ๋์ค์ ์ ์๋ css ์์ฑ์ด ์ด์ ์ ์ธ์ ๋ฎ์ด์ฐ๋ ๋ฐฉ์๊ณผ ์ ์ฌ
์ฌ์ฉ ๋ฐฉ๋ฒ
import styled from 'styled-components';
const Button = styled.button.attrs({
type: 'button',
})`
border: 1px solid #888;
background: transparent;
cursor: pointer;
`;
export default Button;
// button์ ํ์
์ ์ง์ ํ ์ ์์
type ButtonProps = {
type?: 'button' | 'submit' | 'reset';
active?: boolean;
};
// attrs์ <ButtonProps>
const Button = styled.button.attrs<ButtonProps>(props => ({
type: props.type ?? 'button',
}),
// style์ ์ํ <ButtonProps>
)<ButtonProps>`
background: #FFF;
color: #000;
border: 1px solid ${(props: ButtonProps) => (props.active ? '#F00' : '#888')};
${props => props.active && css`
background: #00F;
color: #FFF;
`}
`;
export default function Switch() {
const {value: active, toggle} = useBoolean(false);
return (
// button ํ์
์ ์ง์ ํ์ง ์์ ๊ฒฝ์ฐ, ์คํ์ผ ์ปดํฌ๋ํธ์์ attrs ์ค์ ๋๋ก ์ง์ ๋จ
<Button onClick={toggle} active={active}>
On/Off
</Button>
);
}
Last updated