-
[React] props 와 state 차이점📌 React 2022. 6. 29. 02:36
props 와 state의 차이점?
props, state
데이터를 다룰때 사용되는 개념이다.
일반 JavaScript 객체이다.
차이점?
props는 (함수 매개변수처럼) 컴포넌트에 전달되는 반면,
state는 (함수 내에 선언된 변수처럼) 컴포넌트 안에서 관리한다.
props
부모 컴포넌트가 자식 컴포넌트한테 전달하는 데이터이다.
(자식 컴포넌트 입장에서) 읽기 전용이다.
- 읽기 전용.
- 부모요소에서 설정하는 것.
- propTypes를 통한 props 검사가 가능.
예제
자식 컴포넌트
import React from 'react'; const MyProps = (props) => { return <div>안녕하세요. 제 이름은 {props.name} 입니다.</div>; }; export default MyProps;
부모 컴포넌트
import React from 'react'; import MyProps from './MyProps'; const App = () => { return <MyProps name="리액트" />; }; export default App; // 결과 // 안녕하세요. 제 이름은 리액트 입니다.
state
컴포넌트 내부에서 바뀔 수 있는 값이다.
자신이 들고 있는 값을 말한다.
props 와 비교 했을 때, 쓰기 전용이라고 볼 수 있다.
예제
state 사용 예시
import React, { Component } from 'react'; class Counter extends Component { state = { number: 0 }; handleIncrease = () => { this.setState({ number: this.state.number + 1 }); }; handleDecrease = () => { this.setState({ number: this.state.number - 1 }); }; render() { return ( <div> <h1>카운터</h1> <div>값: {this.state.number}</div> <button onClick={this.handleIncrease}>+</button> <button onClick={this.handleDecrease}>-</button> </div> ); } } export default Counter; import React, { Component } from 'react'; class Counter extends Component { state = { number: 0 }; constructor(props) { super(props); this.handleIncrease = this.handleIncrease.bind(this); this.handleDecrease = this.handleDecrease.bind(this); } handleIncrease() { this.setState({ number: this.state.number + 1 }); } handleDecrease() { this.setState({ number: this.state.number - 1 }); } render() { return ( <div> <h1>카운터</h1> <div>값: {this.state.number}</div> <button onClick={this.handleIncrease}>+</button> <button onClick={this.handleDecrease}>-</button> </div> ); } } export default Counter;
반응형'📌 React' 카테고리의 다른 글
[React] 데이터를 저장하는 방법 (0) 2022.09.27 [React] 데이터 내용을 선택적으로 table 안에 보여주기 (0) 2022.09.27 [React] 리액트 dependency 'react-img-zoom' (0) 2022.06.27 [React] 리액트의 생명 주기 (Life Cycle) (0) 2022.06.27 [React] sh: react-scripts: command not found 오류메시지 (0) 2022.06.08