부모 컴포넌트로 부터 자식 컴포넌트에 데이터를 보낼 수 있게 해주는 방법이다
import './App.css';
import Counter from './counter';
import Container from './Container'
function App() {
const counterProps = {
a:1,
b:2,
C:3,
d:4,
e:5,
inintialValue:5,
}
return (
<Container>
<div>
<Counter {...counterProps}/>
</div>
</Container>
);
}
export default App;
{...counterProps} : 구조 분해 할당으로 props를 자식 컴포넌트에 전달한다
import react,{useState} from 'react'
import OddEvenResult from './OddEvenResult';
const Counter = ({initialValue})=>{
const [count, setCount] = useState(initialValue);
const onIncrease = () =>{
setCount(count +1);
}
const onDecrease = ()=>{
setCount(count -1);
}
return(
<div>
<h2>{count}</h2>
<button onClick={onIncrease}>+</button>
<button onClick={onDecrease}>-</button>
<OddEvenResult count ={count}/>
</div>
)
}
// 기본값 설정해서 에러 방지
Counter.defaultProps = {
initialValue :0,
};
export default Counter;
const Counter = ({initialValue})=>{
const [count, setCount] = useState(initialValue);
자식 컴포넌트에서 props를 받아 사용한다.
// 기본값 설정해서 에러 방지
Counter.defaultProps = {
initialValue :0,
};
undefined가 나오는 경우를 대비해 기본값을 설정해서 에러를 방지한다.