If you need to pass values between components, the props property does this. In React, props and state are two very important properties.

The main difference between state and props is that props are immutable, whereas state can be changed depending on how it interacts 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.

Note: The property is used to set the default value and does not change the value usedprops, change the value usedstate.

  1. Every component object has itprops(propertiesShort for) property;
  2. All attributes of the component tag are stored inprops;
  3. Internally read an attribute value:this.props.propertyName;
  4. What it does: Passes data from component to component via label properties (read only)read only);
  5. rightpropsType and necessity restrictions are carried out for attribute values in.
Person.propTypes = {
    name: React.PropTypes.string.isRequired,
    age: React.PropTypes.number.isRequired
}
Copy the code
  1. Extended properties: Passes all properties of an objectpropspass
<Person {... person}/>Copy the code
  1. Default property value
Person.defaultProps = {
  name: 'Mary'
};
Copy the code

Demo

/* 1. Split component: split interface, extract component * single header component: Welcome * Application component: App 2. Name string * App: props. Names array */

  // Define the internal title component
  class Welcome extends React.Component {
    render() {
      return <h2>Welcome {this.props.name}! </h2>; } } Welcome.propTypes = { name: React.PropTypes.string.isRequired
  };
  // Define external application components
  class App extends React.Component {
    render() {
      return (
        <div>
          {
            this.props.names.map(
              (name, index) => <Welcome name={name} key={index}/>
            )
          }
        </div>
      );
    }
  }
  App.propTypes = {
    names: React.PropTypes.array.isRequired
  };

  var names = ['Tom'.'Jack'."Bob"];
  ReactDOM.render(<App names={names}/>, document.getElementById('example'));
Copy the code