props : 컴포넌트가 버튼으로부터 전달 받는 property. 함수의 첫번째 인자로 들어간다.
<!DOCTYPE html>
<html>
<body>
<div id="root"></div>
</body>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script>
<script type="text/babel">
function Btn({ text, changeValue }) {
console.log(text, "was rendered");
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} fontsize={18}/>
<MemorizedBtn text='Continue' />
</div>
);
}
const root = document.getElementById("root");
ReactDOM.render(<App />, root);
</script>
</html>
⭐️
-부모 컴포넌트 div에서 Btn의 prop으로 "onClick"을 넣는다면 eventlistener가 아니라 Btn안으로 전달되는 prop이름에 불과하다. (실제 HTML에 들어가지 않는다.)
"onClick"이라는 prop을 자식 컴포넌트에 전달해준다음 botton 태그에서 사용해야 한다.
-만약 부모 컴포넌트가 state 변경을 겪으면 모든 자식 컴포넌트들은 리렌더링 된다.
이것은 추후 어플리케이션이 느려지는 원인으로 작용할 수도 있다.
변경되지 않은 자식 컴포넌트의 리렌더링을 막고자 한다면
const MemorizedBtn = React.memo(Btn);
.
.
.
return (
<div>
<MemorizedBtn text={value} changeValue={changeValue} />
<MemorizedBtn text='Continue' />
</div>
);
이처럼 리액트의 memo기능을 사용해야 함.
-proptypes를 지정할 경우 아래 링크를 import해야 한다.
.
.
.
<script src="https://unpkg.com/prop-types@15.7.2/prop-types.js"></script>
.
.
.
Btn.propTypes = {
text: PropTypes.string.isRequired,
fontSize: PropTypes.number.isRequired,
};
function App() {
const [value, setValue] = React.useState("Save Changes");
const changeValue = () => {
setValue("Revert Changes");
};
return (
<div>
<Btn text={"Save Changes"} fontSize={18} />
<Btn text={14} />
</div>
);
text의 proptype을 string으로 지정하면 string으로 지정하지 않을 경우 위의 사진과 같이 에러가 뜬다.(1번째 에러)
또한 isRequired를 지정하면 해당 prop이 없을 경우 에러가 뜬다.(2번째 에러)
-폰트 사이즈의 디폴트값을 전달해줄 수도 있다.
function Btn({ text, fontSize = 16 }) {
.
.
<div>
<Btn text={"Save Changes"} fontSize={18} />
<Btn text={14} />
</div>
첫번째 버튼의 폰트 사이즈는 18이 되고, 두번째 버튼은 디폴트값인 16이 된다.