๐ Props ํ์ฉํ๊ธฐ
Styled Component๋ก ๋ง๋ ์ปดํฌ๋ํธ๋ React ์ปดํฌ๋ํธ์ฒ๋ผ props๋ฅผ ๋ด๋ ค์ค ์ ์๋ค. ๋ด๋ ค์ค props ๊ฐ์ ๋ฐ๋ผ์ ์ปดํฌ๋ํธ๋ฅผ ๋ ๋๋งํ๋ ๊ฒ๋ ๊ฐ๋ฅํ๋ค.
1) Props๋ก ์กฐ๊ฑด๋ถ ๋ ๋๋งํ๊ธฐ
//์ผํญ์ฐ์ฐ์๋ฅผ ํ์ฉํด <Button> ์ปดํฌ๋ํธ์ skyblue ๋ผ๋ props๊ฐ ์๋์ง ํ์ธํ๊ณ ,
//์์ผ๋ฉด ๋ฐฐ๊ฒฝ์์ผ๋ก skyblue๋ฅผ, ์์ ๊ฒฝ์ฐ white๋ฅผ ์ง์ ํด์ฃผ๋ ์ฝ๋.
const Button = styled.button`
background: ${ (props) => props.skyblue? "skyblue" : "white"}
`;
import styled from "styled-components";
import GlobalStyle from "./GlobalStyle";
//๋ฐ์์จ prop์ ๋ฐ๋ผ ์กฐ๊ฑด๋ถ ๋ ๋๋ง์ด ๊ฐ๋ฅํฉ๋๋ค.
const Button1 = styled.button`
background: ${(props) => (props.skyblue ? "skyblue" : "white")};
`;
export default function App() {
return (
<>
<GlobalStyle />
<Button1>Button1</Button1>
<Button1 skyblue>Button1</Button1>
</>
);
}
2) Props ๊ฐ์ผ๋ก ๋ ๋๋งํ๊ธฐ
// 1. props์ ๊ฐ์ ํต์งธ๋ก ํ์ฉํด์ ์ปดํฌ๋ํธ ๋ ๋๋ง์ ํ์ฉํ ์ ์๋ค.
const Button = styled.button`
background: ${(props) => props.color? porps.color : "white"}
`;
// 2. props.color ๊ฐ ์๋ค๋ฉด white๋ฅผ,
//props.color ๊ฐ ์๋ค๋ฉด props.color์ ๊ฐ์ ๊ทธ๋๋ก ๊ฐ์ ธ์์ ์คํ์ผ ์์ฑ ๊ฐ์ผ๋ก ๋ฆฌํด
const Button = styled.button`
background: ${(props) => porps.color || "white"}
`;
import styled from "styled-components";
import GlobalStyle from "./GlobalStyle";
//๋ฐ์์จ prop ๊ฐ์ ๊ทธ๋๋ก ์ด์ฉํด ๋ ๋๋งํ ์๋ ์์ต๋๋ค
const Button1 = styled.button`
background: ${(props) => (props.color ? props.color : "white")};
`;
//๋ค์๊ณผ ๊ฐ์ ํ์์ผ๋ก๋ ํ์ฉํ ์ ์์ต๋๋ค.
const Button2 = styled.button`
background: ${(props) => props.color || "white"};
`;
export default function App() {
return (
<>
<GlobalStyle />
<Button1>Button1</Button1>
<Button1 color="orange">Button1</Button1>
<Button1 color="tomato">Button1</Button1>
<br />
<Button2>Button2</Button2>
<Button2 color="pink">Button2</Button2>
<Button2 color="turquoise">Button2</Button2>
</>
);
}
4. ์ ์ญ ์คํ์ผ ์ค์ ํ๊ธฐ
1. ์ ์ญ ์คํ์ผ์ ์ค์ ํ๊ธฐ ์ํด Styled Components์์ createGlobalStyle ํจ์๋ฅผ ๋ถ๋ฌ์จ๋ค.
import { createGlobalStyle } from "styled-components";
2. ํจ์๋ฅผ ์ฌ์ฉํด CSS ํ์ผ์์ ์์ฑํ๋ฏ ์ค์ ํด์ฃผ๊ณ ์ถ์ ์คํ์ผ์ ์์ฑํ๋ค.
const GlobalStyle = createGlobalStyle`
button {
padding : 5px;
margin : 2px;
border-radius : 5px;
}
`
3. <GlobalStyle> ์ปดํฌ๋ํธ๋ฅผ ์ต์์ ์ปดํฌ๋ํธ์์ ์ฌ์ฉํด์ฃผ๋ฉด ์ ์ญ์ <GlobalStyle> ์ปดํฌ๋ํธ์ ์คํ์ผ์ด ์ ์ฉ๋๋ค.
function App() {
return (
<>
<GlobalStyle />
<Button>์ ์ญ ์คํ์ผ ์ ์ฉํ๊ธฐ</Button>
</>
);
}
'React' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
React ์ํ๊ด๋ฆฌ (0) | 2022.07.07 |
---|---|
Cmarket (Hooks ๋ฒ์ )/ useEffect (0) | 2022.07.06 |
[React] CDD ๊ฐ๋ฐ ๋๊ตฌ Styled Components (0) | 2022.07.01 |
[React] ์ปดํฌ๋ํธ ์ฃผ๋ ๊ฐ๋ฐ Component Driven Development (CDD) (0) | 2022.06.30 |
React event.target.value (0) | 2022.06.30 |