React Props


The main difference between state and props is that props are immutable, while state can change based on interaction with the user. This is why some container components need to define state to update and modify data. Subcomponents can only pass data through props.


Using Props

The following example demonstrates how to use props in a component:

Example

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>php中文网 React 实例</title>
    <script src="http://static.php.cn/assets/react/react-0.14.7/build/react.min.js"></script>
    <script src="http://static.php.cn/assets/react/react-0.14.7/build/react-dom.min.js"></script>
    <script src="http://static.php.cn/assets/react/browser.min.js"></script>
  </head>
  <body>
    <div id="example"></div>
    <script type="text/babel">
      var HelloMessage = React.createClass({
        render: function() {
          return <h1>Hello {this.props.name}</h1>;
        }
      });

      ReactDOM.render(
        <HelloMessage name="php" />,
        document.getElementById('example')
      );
    </script>
  </body>
</html>

Run instance»

Click the "Run instance" button to view the online instance

The name attribute in the instance is obtained through this.props.name.


Default Props

You can set default values ​​for props through the getDefaultProps() method. The example is as follows:

Example

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>php中文网 React 实例</title>
    <script src="http://static.php.cn/assets/react/react-0.14.7/build/react.min.js"></script>
    <script src="http://static.php.cn/assets/react/react-0.14.7/build/react-dom.min.js"></script>
    <script src="http://static.php.cn/assets/react/browser.min.js"></script>
  </head>
  <body>
    <div id="example"></div>
    <script type="text/babel">
      var HelloMessage = React.createClass({
      getDefaultProps: function() {
        return {
          name: 'php'
        };
      },
      render: function() {
        return <h1>Hello {this.props.name}</h1>;
      }
    });

    ReactDOM.render(
      <HelloMessage />,
      document.getElementById('example')
    );
    </script>
  </body>
</html>

Run Instance»

Click the "Run Instance" button to view the online instance


State and Props

The following instances Demonstrates how to combine state and props in your application. We can set state in the parent component and pass it to the child component using props on the child component. In the render function, we set name and site to get the data passed by the parent component.

Instance

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>php中文网 React 实例</title>
    <script src="http://static.php.cn/assets/react/react-0.14.7/build/react.min.js"></script>
    <script src="http://static.php.cn/assets/react/react-0.14.7/build/react-dom.min.js"></script>
    <script src="http://static.php.cn/assets/react/browser.min.js"></script>
  </head>
  <body>
    <div id="example"></div>
    <script type="text/babel">
    var WebSite = React.createClass({
      getInitialState: function() {
        return {
          name: "php中文网",
          site: "//m.sbmmt.com"
        };
      },
     
      render: function() {
        return (
          <div>
            <Name name={this.state.name} />
            <Link site={this.state.site} />
          </div>
        );
      }
    });

    var Name = React.createClass({
      render: function() {
        return (
          <h1>{this.props.name}</h1>
        );
      }
    });

    var Link = React.createClass({
      render: function() {
        return (
          <a href={this.props.site}>
            {this.props.site}
          </a>
        );
      }
    });

    React.render(
      <WebSite />,
      document.getElementById('example')
    );
    </script>
  </body>
</html>

Run Instance»

Click the "Run Instance" button to view the online instance


Props verification

Props verification uses propTypes, which can ensure that our application components are used correctly. React.PropTypes provides many validators (validators) to verify the incoming Whether the data is valid. The JavaScript console will throw a warning when invalid data is passed to props.

The following example creates a Mytitle component. The attribute title is required and is a string. If it is a number, an error will be reported:

Example

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>php中文网 React 实例</title>
    <script src="http://static.php.cn/assets/react/react-0.14.7/build/react.js"></script>
    <script src="http://static.php.cn/assets/react/react-0.14.7/build/react-dom.js"></script>
    <script src="http://static.php.cn/assets/react/browser.min.js"></script>
  </head>
  <body>
	  <div id="example"></div>
    <script type="text/babel">
    var title = "php中文网";
    // var title = 123;
    var MyTitle = React.createClass({
      propTypes: {
        title: React.PropTypes.string.isRequired,
      },

      render: function() {
         return <h1> {this.props.title} </h1>;
       }
    });
    ReactDOM.render(
        <MyTitle title={title} />,
        document.getElementById('example')
    );
    </script>
  </body>
</html>

Run instance»

Click the "Run instance" button to view the online instance

If title uses a numeric variable, the following error message will appear on the console:

Warning: Failed propType: Invalid prop `title` of type `number` supplied to `MyTitle`, expected `string`.

More validator descriptions are as follows:

React.createClass({
  propTypes: {
    // 可以声明 prop 为指定的 JS 基本数据类型,默认情况,这些数据是可选的
   optionalArray: React.PropTypes.array,
    optionalBool: React.PropTypes.bool,
    optionalFunc: React.PropTypes.func,
    optionalNumber: React.PropTypes.number,
    optionalObject: React.PropTypes.object,
    optionalString: React.PropTypes.string,

    // 可以被渲染的对象 numbers, strings, elements 或 array
    optionalNode: React.PropTypes.node,

    //  React 元素
    optionalElement: React.PropTypes.element,

    // 用 JS 的 instanceof 操作符声明 prop 为类的实例。
    optionalMessage: React.PropTypes.instanceOf(Message),

    // 用 enum 来限制 prop 只接受指定的值。
    optionalEnum: React.PropTypes.oneOf(['News', 'Photos']),

    // 可以是多个对象类型中的一个
    optionalUnion: React.PropTypes.oneOfType([
      React.PropTypes.string,
      React.PropTypes.number,
      React.PropTypes.instanceOf(Message)
    ]),

    // 指定类型组成的数组
    optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),

    // 指定类型的属性构成的对象
    optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number),

    // 特定 shape 参数的对象
    optionalObjectWithShape: React.PropTypes.shape({
      color: React.PropTypes.string,
      fontSize: React.PropTypes.number
    }),

    // 任意类型加上 `isRequired` 来使 prop 不可空。
    requiredFunc: React.PropTypes.func.isRequired,

    // 不可空的任意类型
    requiredAny: React.PropTypes.any.isRequired,

    // 自定义验证器。如果验证失败需要返回一个 Error 对象。不要直接使用 `console.warn` 或抛异常,因为这样 `oneOfType` 会失效。
    customProp: function(props, propName, componentName) {
      if (!/matchme/.test(props[propName])) {
        return new Error('Validation failed!');
      }
    }
  },
  /* ... */
});