React Props

This section describes React Props.

The main difference between state and props is that props are immeascondable, and state can be changed based on interaction with the user. T hat's why some container components need to define state to update and modify data. Child components, on the other, can only pass data through state.


Use Props

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

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

ReactDOM.render(
  <HelloMessage name="W3CSchool" />,
  document.getElementById('example')
);

Try it out . . .

The name property in the instance is this.props.name the file.


The default Props

You can set the default value for props using the getDefaultProps() method, as follows:

var HelloMessage = React.createClass({
  getDefaultProps: function() {
    return {
      name: 'W3CSchool'
    };
  },
  render: function() {
    return <h1>Hello {this.props.name}</h1>;
  }
});

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

Try it out . . .


State and Props

The following example shows how to combine state and props in your app. W e can set state in the parent component and pass it to the child component by using props on the child component. In the render function, we set name and site to get the data passed by the parent component.

var WebSite = React.createClass({
  getInitialState: function() {
    return {
      name: "W3Cschool教程",
      site: "https://www.w3cschool.cn"
    };
  },
 
  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>
    );
  }
});

ReactDOM.render(
  <WebSite />,
  document.getElementById('example')
);

Try it out . . .


Props validation

Props verifies the use of propTypes, which guarantees that our application components are used correctly, and React.PropTypes provides a number of validators to verify that the incoming data is valid. When invalid data is passed in to props, the JavaScript console throws a warning.

The following instance creates a Mytitle component, the property title is required and is a string, and non-string types are automatically converted to strings:

var title = "W3Cschool教程";
// var title = 123;
var MyTitle = React.createClass({
  propTypes: {
    title: React.PropTypes.string.isRequired,
  },

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

Try it out . . .

If title uses numeric variables, the console will see the following error message:

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

More validator instructions 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!');
      }
    }
  },
  /* ... */
});