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
.
- Every component object has it
props
(properties
Short for) property; - All attributes of the component tag are stored in
props
; - Internally read an attribute value:
this.props.propertyName
; - What it does: Passes data from component to component via label properties (read only)
read only
); - right
props
Type 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
- Extended properties: Passes all properties of an object
props
pass
<Person {... person}/>Copy the code
- 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