헉!!/ETC
[React] Props
권태성
2024. 7. 21. 00:09
컴포넌트에 데이터를 전달하는 방법
컴포넌트를 호출하는 곳에서 아래와 같이 컴포넌트에 초기 값을 전달할 수 있음
function App() {
const number = 5;
return (
<div>
<MyHeader />
<Counter a={1} initialValue={number} />
</div>
);
}
컴포넌트에서는 인자로 받아서 사용이 가능함.
import React, { useState } from "react";
const Counter = (props) => {
console.log(props);
const [count, setCount] = useState(props.initialValue);
const onIncrease = () => {
setCount(count + 1);
};
const onDecrease = () => {
setCount(count - 1);
};
return (
<div>
<h2>{count}</h2>
<button onClick={onIncrease}>+</button>
<button onClick={onDecrease}>-</button>
</div>
);
};
export default Counter;
아래와 같이 스프레드 연산자로 값을 전달할 수도 있음
function App() {
const number = 5;
const counterProps = {
a: 1,
b: 2,
c: 3,
d: 4,
e: 5,
initialValue: number,
};
return (
<div>
<MyHeader />
<Counter {...counterProps} />
</div>
);
}
받는 쪽에서는 비구조화 할당으로 필요한 prop만 꺼내서 받을 수도 있음
import React, { useState } from "react";
const Counter = ({ initialValue }) => {
console.log(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>
</div>
);
};
export default Counter;
Prop로 아무것도 전달하지 않으면 undefined가 전달되니 주의해야함.
Counter.defaultProps = {
initialValue: 0,
};
위와 같이 defaultProps를 지정하여 예외를 방지할 수 있음.
React는 자기가 가진 State가 바뀌면 리렌더링이 되고
자신에게 전달되는 Props가 바뀌면 리렌더링이 되고
내 부모 컴포넌트가 변경되어도 리렌더링이 됨
728x90