Latest web development tutorials

React Props

The main difference between the state and propsprops that are immutable, while state can interact with the user to change.This is why some container components need to define state to update and modify the data. The sub-assembly can only pass data through props.


Use Props

The following example demonstrates how to use props in the assembly:

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

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

try it"

This.props.name instance name attribute to get through.


Default Props

You can set the default values ​​for the props by getDefaultProps () method, examples are as follows:

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

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

try it"


State and Props

The following example demonstrates how to use a combination of state and props in the application. We can set up state in the parent assembly, and through the use of props in the sub-assembly to be transferred to the sub-assembly. In the render function, we set the name and site to get the parent component passes over the data.

var WebSite = React.createClass({
  getInitialState: function() {
    return {
      name: "本教程",
      site: "http://www.w3big.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')
);

try it"


Props verification

Props authentication usespropTypes, it can ensure that our application components are used correctly, React.PropTypes offers many validator (validator) to validate incoming data is valid.When the props invalid incoming data, JavaScript Console will throw a warning.

The following example creates a Mytitle component, property title is a must and is a string, a number will be given if it is:

var title = "本教程";
// 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')
);

try it"

If the title using the numeric variables, console the following error message:

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