The child can only change the parent’s state by onClick, which means that the parent has declared a function or method as a contract to describe how its state will change, and then gives it to the child to use as a property. This leads to a pattern: data is always distributed one-way from the top level down, but only subcomponent callbacks can conceptually go back to the state top level to affect the data. So state is kind of reactive.
The parent component:
import React, { Component } from 'react';
import AddButton from './AddButton';
class App extends Component {
constructor(props) {
super(props);
this.state = {
username: 'Lily'.age: 18
}
this.handlerClick = this.handlerClick.bind(this);
}
handlerClick(e){
this.setState({
age: this.state.age+1
});
}
render() {
return (
<div>
<AddButton func={this.handlerClick}/>
<span onClick={this.handlerClick}>Parent component: {this.state.username+'-- '+this.state.age}</span>
</div>)}}export default App;
Copy the code
Child components:
import React from 'react'
function AddButton(props) {
return (
<div>
<span>Child components:</span>
<button onClick={props.func}>+ 1</button>
</div>)}export default AddButton;
Copy the code