TIL React # 5 props

JohnKim·2021년 6월 4일
0

React

목록 보기
5/11
post-thumbnail

props

props는 단어 뜻 그래로 컴포넌트의 속성값을 의미한다.

부모 컴포넌트로 부터 전달 받은 데이터를 지니고 있는 객체이다.

props 사용하기

1.부모 컴포넌트가 있어야함

2.부모 컴포넌트와 import 되어 있는 자식 컴포넌트에서 사용함

3.부모 컴포넌트인 parent 컴포넌트에 color state가 있고 valus는 red이다.

4.자식 컴포넌트인 Child 컴포넌트에 <Child titleColor={this.state.color}/>를 작성하여 부모컴포넌트의 state를 전달한다.
5. 자식컴포넌트의 버튼을 누르면 색상이 변하게하는 event handler 함수를 생성하고
자식 컴포넌트에 changeColor={this.handleColor} 로 전달한다.


import React from 'react';
import Child from '../pages/Children/Children';

class Parent extends React.Component {
  constructor() {
    super();
    this.state = {
      color: 'red'
    };
  }
  
  handleColor = () => {
    this.setState({
      color: 'blue'
    })
  }

  render() {
    return (
      <div>
        <h1>Parent Component</h1>
	<Child titleColor={this.state.color} changeColor={this.handleColor}/>
      </div>
    );
  }
}

export default State;

6.자식컴포넌트에는 부모로 받은 state를 this.props.state를 통해 받아올수 있다.
부모컴포넌트로 부터 받은 event handler함수 또한 Child 컴포넌트 내 onClick이벤트에 적용시킬수 있다. 물론 이곳에도 this.props는 붙여주어야 한다.

import React from 'react';

class Child extends React.Component {
  render() {
		// console.log(this.props);

    return (
      <div>
        <h1 style={{color : this.props.titleColor}}>Child Component</h1>
        <button onClick={this.props.changeColor}>Click</button>
     </div>
    );
  }
}

export default State;

props를 사용하기전에 state를 생성하는 위치에서 부터 내가 지금 사용할 컴포넌트 까지 state가 순차적으로 잘 넘어오고 있는지 확인해야 한다. 만약 부모의 자식의 자식컴포넌트에서 state를 사용하고 싶다면 중간의 자식컴포넌트에서도 this.proprs를 사용하여 자식의 자식 컴포넌트에 전달해주어야한다.

0개의 댓글