The communication between the React subcomponent and the parent component includes the following aspects:
1. The child component gets the parent component property: props or state 2. Method of child component calling parent component 3. The parent component gets the properties of the child component: props or state 4. Method of parent component calling child component
Let's take a look at this example in detail:
Parent component
var Father = React.createClass({
getDefaultProps: function () {
return {
name: "Parent component"
}
},
MakeMoney: function () { // Earn money for subcomponent calls
alert("I'm making money.!");
},
CheckStudy: function () { // Learning, calling subcomponent methods
this.refs["child"].Study();
},
getChildName: function () { // Call subcomponent method to get child name
alert(this.refs["child"].getName());
},
render: function () {
return <div>
<button onClick={this.CheckStudy}>Monitor children's learning</button>
<button onClick={this.getChildName}>Get the child's name</button>
<br/>
//Sub components
<Child ref="child" fatherName={this.props.name} MakeMoney={this.MakeMoney}></Child>
</div>;
}
});
Sub components
var Child = React.createClass({
getDefaultProps: function () {
return {
name: "Sub components"
}
},
StudyMakeMoney: function () { // Learn to earn money and call the parent component method
this.props.MakeMoney();
},
Study: function () { // Learning, calling subcomponent methods
alert("I'm studying!");
},
getName: function () {// For parent component call, return name
return this.props.name;
},
render: function () {
return <div>Parent component name:{this.props.fatherName}
<button onClick={this.StudyMakeMoney}>Children learn to earn money</button>
</div>;
}
});
Corresponding
1. Child gets props of the parent component through the name passed in by the parent component 2. The Child component calls the parent component method through the MakeMoney method passed in by the parent component 3. The parent component, Father, calls the getName method of the child component through ref to get props 4. The parent component, the parent component, calls the Study method of the child component through ref