
- 컴포넌트 간의 효율적인 데이터 흐름을 가능하게 하는 객체
- 단방향 데이터 : 부모 컴포넌트에서 자식 컴포넌트로 데이터를 전달할 때 사용
- 읽기 전용 데이터 : 자식 컴포넌트에서는 데이터 변경할 수 없다.
(props는 순수 함수처럼 동작해야된다.)- props는 정적인 데이터를 전달한다.
- props를 전달할 때는 문자열을 제외하고는
{ }에 담아서 전달해야 한다.
// 부모 컴포넌트
class App extends React.Component {
render() {
return <Body content="안녕" />;
}
}
// 자식 컴포넌트
class Body extends React.Component {
render() {
return <div>{this.props.content}</div>;
}
}
App이라는 부모 컴포넌트에서 자식 컴포넌트 Body로 content = "안녕" 이라는 데이터를 전송하고 있다.
전송받은 props 데이터는 this.props 키워드를 통해 호출할 수 있다.
// 부모 컴포넌트
function App(){
return(
<Body content="안녕" />;
);
}
// 자식 컴포넌트
function Body(props){
return(
<div>{props.content}</div>;
);
}
함수형 컴포넌트도 클래스형 컴포넌트와 마찬가지로 부모 컴포넌트에서 자식 컴포넌트로 props를 전달한다. 차이점은 this를 사용할 필요가 없다.
- state는 컴포넌트 내부에서 동적인 데이터를 다룬다.
- 컴포넌트 안에서 데이터를 변경할 수 있다.
setState()로 state를 변경한다.- setState로 state 변경 시 컴포넌트가 리렌더링 된다.
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
incrementCount = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.incrementCount}>Increment</button>
</div>
);
}
}
클래스 컴포넌트에서 state는 생성자(constructor) 내부에서 초기 상태(state)를 설정한 후에 this.state로 호출한다.
setState(updater, [callback])구조로 state를 변경할 수 있다.
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
const incrementCount = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={incrementCount}>Increment</button>
</div>
);
};
함수형 컴포넌트에서는 State를 사용하기 위해 useState라는 훅(Hook)을 사용한다.
const [state, setState] = useState(initialState); 구조로 상태를 설정한다.
* 참고 :
https://ko.legacy.reactjs.org/docs/components-and-props.html
https://ko.legacy.reactjs.org/docs/components-and-props.html
https://minjung-jeon.github.io/React-props-state/
https://firework-ham.tistory.com/29