English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

ReactJS 프로퍼티(Props)

상태와道具 간의 주요 차이점props불변입니다. 이는 컨테이너 컴포넌트가 업데이트 및 변경이 가능한 상태를 정의해야 하며, 서브 컴포넌트는 상태를 전달받는 prop만 사용해야 하는 이유입니다.

프로퍼티 사용

컴포넌트에서 불변 데이터를 사용해야 할 때, 우리는 main.js의 reactDOM.render() 함수에道具를 추가하고 컴포넌트에서 사용할 수 있습니다.

App.jsx

import React from 'react';
class App extends React.Component {
   render() {
      return (
         <div>
            <h1>{this.props.headerProp}</h1>
            <h2>{this.props.contentProp}</h2>
         </div>
      );
   }
}

main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from '.'/App.jsx';
ReactDOM.render(<App headerProp="Header from props..." contentProp="Content
   from props..."/> document.getElementById('app'));
export default App;

이렇게 하면 다음과 같은 결과가 발생합니다.

기본道具

컴포넌트 생성자 함수에 직접 기본 속성 값을 설정할 수도 있으며, 이를 reactDom.render() 요소에 추가하지 않아도 됩니다.

App.jsx

import React from 'react';
render() {
      return (
         <div>
            <h1>{this.props.headerProp}</h1>
            <h2>{this.props.contentProp}</h2>
         </div>
      );
   }
}
class App extends React.Component {
   App.defaultProps = {
   headerProp: "Header from props...",
}
export default App;

main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from '.'/App.jsx';
ReactDOM.render(<App/> document.getElementById('app'));

contentProp: "Content from props..."

출력이 이전과 동일하다는 것을 보여줍니다.

다음 예제는 상태와道具상태응용 프로그램에서 병합 및 지원을 합니다. 우리는 부모 컴포넌트에서 상태를 설정한 후 사용합니다.props그것을 컴포넌트 트리에 전달합니다.render함수 내부에서 우리는 설정하고 있습니다.headerPropcontentProp서브 컴포넌트에서 사용됩니다.

App.jsx

import React from 'react';
class App extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
         header: "Header from props..."
         content: "Content from props..."
      }
   }
   render() {
      return (
         <div>
            <Header headerProp={this.state.header}/>
            <Content contentProp={this.state.content}/>
         </div>
      );
   }
}
class Header extends React.Component {
   render() {
      return (
         <div>
            <h1>{this.props.headerProp}</h1>
         </div>
      );
   }
}
class Content extends React.Component {
   render() {
      return (
         <div>
            <h2>{this.props.contentProp}</h2>
         </div>
      );
   }
}
export default App;

main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from '.'/App.jsx';
ReactDOM.render(<App/> document.getElementById('app'));

결과는 전 두 예제와 동일하지만, 유일한 차이점은 우리의 데이터 소스입니다. 이 데이터 소스는 원래상태그러면, 그것을 업데이트하려면, 우리는 단지 상태를 업데이트하면 됩니다. 모든 자식 컴포넌트가 업데이트됩니다.