Reactjs-props-overview

提供:Dev Guides
移動先:案内検索

ReactJS-小道具の概要

stateとpropsの主な違いは、 props が不変であることです。 これが、コンテナコンポーネントが更新および変更可能な状態を定義する必要があるのに対し、子コンポーネントはpropsを使用して状態からのデータのみを渡す必要があるためです。

小道具の使用

コンポーネントに不変データが必要な場合は、 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>
      );
   }
}
export default App;

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;

これにより、次の結果が生成されます。

React Propsの例

デフォルトの小道具

また、* 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>
      );
   }
}
App.defaultProps = {
   headerProp: "Header from props...",
   contentProp:"Content 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'));

出力は以前と同じです。

React Propsの例

状態と小道具

次の例は、アプリで state とpropsを組み合わせる方法を示しています。 親コンポーネントに状態を設定し、 props を使用してコンポーネントツリーに渡します。 render 関数内で、子コンポーネントで使用される headerProp および contentProp を設定しています。

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'));

結果は前の2つの例と同じになりますが、異なるのはデータのソースのみで、現在は元は state からのものです。 更新する場合は、状態を更新するだけで、すべての子コンポーネントが更新されます。 詳細については、イベントの章をご覧ください。

React Propsの例