props
function Btn({ value, changeValue }) {
return (
<button
onClick={changeValue}
style={{
backgroundColor: "tomato",
color: "white",
padding: "10px 20px",
border: 0,
borderRadius: 10,
}}
>
{value}
</button>
);
}
function App() {
const [value, setValue] = React.useState("Save Changes");
const changeValue = () => setValue("Revert Changes");
return (
<div>
<Btn value="Save Changes" onClick={changeValue} />
<Btn value="Confirm" />
</div>
);
}
const root = document.querySelector("#root");
ReactDOM.render(<App />, root);
memo
function Btn({ text, changeValue }) {
console.log(text);
return (
<button
onClick={changeValue}
style={{
backgroundColor: "tomato",
color: "white",
padding: "10px 20px",
border: 0,
borderRadius: 10,
}}
>
{text}
</button>
);
}
function App() {
const [value, setValue] = React.useState("Save Changes");
const changeValue = () => setValue("Revert Changes");
return (
<div>
<Btn text={value} changeValue={changeValue} />
<Btn text="Confirm" />
</div>
);
}
const root = document.querySelector("#root");
ReactDOM.render(<App />, root);
React.memo()의 인자로 컴포넌트를 넣어주고 만든 변수를 컴포넌트로 쓰면 된다.
function Btn({ text, changeValue }) {
console.log(text);
return (
<button
onClick={changeValue}
style={{
backgroundColor: "tomato",
color: "white",
padding: "10px 20px",
border: 0,
borderRadius: 10,
}}
>
{text}
</button>
);
}
const MemorizedBtn = React.memo(Btn);
function App() {
const [value, setValue] = React.useState("Save Changes");
const changeValue = () => setValue("Revert Changes");
return (
<div>
<MemorizedBtn text={value} changeValue={changeValue} />
<MemorizedBtn text="Confirm" />
</div>
);
}
const root = document.querySelector("#root");
ReactDOM.render(<App />, root);
Props Types
앱이 커짐에 따라 타입 검사를 활용하면 많은 버그를(bug) 잡을 수 있다.
컴포넌트.propTypes으로 객체를 생성하여 타입을 설정 할 수 있다.
- 타입뿐만아니라 isRequired를 설정 할 수 있다.
- text: PropTypes.string.isRequired
- default를 설정 해 주고 싶으면 { text, fontSize = 16 } 와 같이 설정하면 된다.
function Btn({ text, fontSize = 16 }) {
return (
<button
style={{
backgroundColor: "tomato",
color: "white",
padding: "10px 20px",
border: 0,
borderRadius: 10,
fontSize,
}}
>
{text}
</button>
);
}
Btn.propTypes = {
text: PropTypes.string.isRequired,
fontSize: PropTypes.number,
};
function App() {
return (
<div>
<Btn text="Save Changes" fontSize={18} />
<Btn text="Confirm" />
</div>
);
}
const root = document.querySelector("#root");
ReactDOM.render(<App />, root);