[React JS] props

Kim Ji Yun·2022년 1월 23일
0
post-thumbnail

props란?

  • 컴포넌트 내부의 Immutable Data로 변화하지 않는 데이터를 처리할 때 사용됨.
  • JSX 내부에 { this.props.propsName }
  • 컴포넌트를 사용할 때, <> 괄호 안에 propsName="value"
  • this.props.children은 모든 컴포넌트가 기본적으로 갖고있는 props이며, <컵포넌트> </컴포넌트> 사이에 값이 들어감.
class Codelab extends React.Component { 
  render() {
    return (
      <div>
        <h1>Hello {this.props.name}</h1> 
        <div>{this.props.children}</div>
      </div>
    ); 
  }
}

class App extends React.Component {
  render() {
    return (
      <Codelab name="velopert">이 사이에 있는게 props.children</Codelab>
    );
  }
}


ReactDOM.render(<App/>, document.getElementById('root'));

Type 검증

  • 특정 props값이 특정 type이 아니거나, 필수 props인데 입력하지 않았을 경우, console창에서 경고 표시 출력
  • type를 검증할 때는 컴포넌트 선언이 끝난 후, props.propTypes 객체를 설정
class App extends React.Component{
  render() {
    return (
      <div>
        {this.props.value}
        {this.props.secondValue}
        {this.props.thirdValue}
      </div>
    );
  }
};

App.propTypes = {
  value: React.PropTypes.string,
  secondValue: React.PropTypes.number;
  thirdValue: React.PropTypes.any.isRequired
};

propTypes 설정은 필수가 아니며 유지보수와 효과적인 활용을 위해 설정한다.

0개의 댓글

관련 채용 정보