
부모 컴포넌트로부터 자식 컴포넌트에 데이터를 보낼 수 있게 해주는 방법 (어떤 형태로든 보낼 수 있음)
자식 컴포넌트의 첫 번째이자 유일한 인자
버튼을 만들때마다 일일히 style 적용 -> 비효율적
=> 하나의 틀로 만들어 붙이면 좋겠다..!
전달할 property = 값<Btn tomato='Save Changes' />
{props.text} 형태로 사용function Btn(props) {
return <button
onClick={changeValue}
style={{
backgroundColor: 'tomato',
color: 'white',
padding: '10px 20px',
borderRadius: 10,
border: 0
}}>
{props.text}
</button>
}
{}와 함께 바로 사용function Btn({ text, changeValue }) {
return <button
onClick={changeValue}
style={{
backgroundColor: 'tomato',
color: 'white',
padding: '10px 20px',
borderRadius: 10,
border: 0
}}>
{text}
</button>
}
Continue 버튼은 idex 값을 전달하지 않아 undefined 를 받게됨
-> default 값을 설정할 수 있음
<Btn text="Save Changes" index={1}/>
<Btn text="Continue"/>
// default 값 설정
function Btn({text, fontSize = 14}) { ... }
function Btn({text, changeValue}) {
return (
// changeValue 함수를 받아와 버튼 onClick 에 적용
<button
onClick={changeValue}
style={{
backgroundColor: "tomato",
color: "white",
padding: "10px 20px",
border: 0,
borderRadius: 10,
}}>{text}</button>
)
}
function App() {
// state 이용해 버튼 상태 저장
const [value, setValue] = React.useState("Save Changes")
// changeValue() : setValue 함수를 이용해 Revert Changes 로 바꾸는 함수
const changeValue = () => setValue("Revert Changes")
return (
<div>
// Btn 컴포넌트로 value 와 changeValue 넘겨줌
<Btn text={value} changeValue={changeValue}/>
<Btn text="Continue"/>
</div>
);
}
onClick 을 button 안에 넣는다면 HTML 요소이지만,
내 커스텀 컴포넌트에다가 넣는다면 이벤트리스너가 아니라 하나의 props 일 뿐
function Btn({text, changeValue}) {
return (
// changeValue 함수를 받아와 버튼 onClick 에 적용
<button
onClick={changeValue}
style={{
backgroundColor: "tomato",
color: "white",
padding: "10px 20px",
border: 0,
borderRadius: 10,
}}>{text}</button>
)
}
: 어떤 타입의 prop 을 받고 있는지 체크해줌
why? ReactJS 는 유효한 코드라고 감지해 UI 상에서 잘못된 점을 알려주지 않음
Btn.propTypes = {
text: PropTypes.string,
fontSize: PropTypes.number
}
// fontSize는 number 값 입력해야함. 문자열 입력 발생시 경고문
<Btn text="Continue" fontSize={"hi"}/>
📚 노마드 코더 <ReactJS로 영화 웹 서비스 만들기>
👩💻 참고