const Button = () => { return <button>ํด๋ฆญ</button>; }; export default Button;
import Button from "./components/button"; function App() { return ( <> <Button /> <Button /> <Button /> </> ); }
function App() { return ( <> <Button text={"๋ฉ์ผ"} color={"red"}/> <Button text={"์นดํ"} /> <Button text={"๋ธ๋ก๊ทธ"} /> </> ); }const Button = (props) => { console.log(props); return <button>ํด๋ฆญ</button>; };โ text์ ๊ฐ์ ๋ฐ์ผ๋ ค๋ฉด ์ปดํฌ๋ํธ์ ๋งค๊ฐ๋ณ์(props)๋ฅผ ์ ๋ ฅํด์ค์ผํ๋ค.
โ ๊ฐ์ด ๊ฐ์ฒด ํํ๋ก ๋ด๊ฒจ์ ์ ๋ฌ๋๋ค.
โ Props ๊ฐ๋ค์ด properties๋ก ํ๋์ฉ ๋ค์ด๊ฐ์๋ค.
const Button = (props) => { console.log(props); return ( <button style={{ color: props.color }}> {props.text} - {props.color.toUpperCase()} </button> ); };
function App() {
return (
<>
<Button text={"๋ฉ์ผ"} color={"red"} />
<Button text={"์นดํ"} />
<Button text={"๋ธ๋ก๊ทธ"} />
</>
);
}
์์ ๊ฐ์ด ์์ฑ์ ํ๋ฉด ์ค๋ฅ๊ฐ ๋ฐ์ํ๋ค
โ ์ด์ : ์นดํ, ๋ธ๋ก๊ทธ์๋ color ๊ฐ์ด ์๊ธฐ ๋๋ฌธ์ด๋ค.(Undefined)
โ ํด๊ฒฐ ๋ฐฉ์ : ์๋์ผ๋ก ์ค์ ๋ ๊ธฐ๋ณธ ๊ฐ์ ์ค์
>```
Button.defaultProps = {
color: "black",
};
โ ๋ชจ๋ ๋ฒํผ์ defualt ๊ฐ์ black์ผ๋ก ์ง์
const Button = ({ text = "๊ธฐ๋ณธ ํ ์คํธ", color = "black" }) => { console.log(text, color); return ( <button style={{ color: color }}> {text} - {color.toUpperCase()} </button> ); };
โ default ๊ฐ์ ๋งค๊ฐ๋ณ์์ ํจ๊ป ์์ฑ
const Button = ({ text, color }) => { console.log(text, color); return ( <button style={{ color: color }}> {text} - {color.toUpperCase()} </button> ); };
function App() { const buttonProps = { text: "๋ฉ์ผ", color: "red", a: 1, b: 2, c: 3, }; return ( <> <Button {...buttonProps} /> <Button text={"์นดํ"} /> <Button text={"๋ธ๋ก๊ทธ"} /> </> ); }
++ ๊ฐ์์์๋ ์ค๋ฅ์์ด ์ ๋ฌ์ง๋ง ๋๋ text, color ๊ฐ๋ง ๋์ค๊ณ a,b,c ๊ฐ์ ๋์ค์ง์์์
๊ทธ๋ฅ Button ์ปดํฌ๋ํธ์ ๋งค๊ฐ๋ณ์(โฆrest)๋ฅผ ์ถ๊ฐํ์ฌ ๊ฐ์ด ๋์ค๋๋ก ํ์๋ค.
<Button></Button> ์ผ๋ก ์
ํ ํฌ๋ก์งํ์ง ์๊ณ ๊ทธ ์์ ์์ ํ๊ทธ๋ ์ปดํฌ๋ํธ๋ฅผ ์
๋ ฅํ ์ ์๋ค.function App() { const buttonProps = { text: "๋ฉ์ผ", color: "red", }; return ( <> <Button {...buttonProps} /> <Button text={"์นดํ"} /> <Button text={"๋ธ๋ก๊ทธ"}> <Header /> </Button> </> ); } -- const Button = ({ text = "๊ธฐ๋ณธ ํ ์คํธ", color = "black", children }) => { console.log(text, color); return ( <button style={{ color: color }}> {text} - {color.toUpperCase()} {children} </button> ); };
โ Header๋ Button์ ์์์ด๋ฏ๋ก Button ์ปดํฌ๋ํธ ๋งค๊ฐ๋ณ์์ children ์ถ๊ฐ
โ children ๊ฐ์ ์ถ๋ ฅ