原理:通过props将父组件中的方法传给子组件实现。
父组件:
class Parent extends React.Component{
constructor(){
super();
this.state={
count: 0
}
}
increase(e){
this.setState({
count: this.state.count+e
})
}
render(){
return (
<div>
<p onClick={()=>this.increase(2)}>{this.state.count}</p>
<Children increment={this.increase.bind(this)}/>
</div>
)
}
}
子组件:
class Children extends React.Component{
constructor(){
super();
}
render(){
return (
<button onClick={this.props.increment.bind(this, 2)}>增长</button>
)
}
}