1. 前言
1.之前写过一篇粗浅的文章 react父子组件传值
2.但是这篇文章子组件修改父组件的时候没有传值,这篇文章补上
2. 先看父组件 bind的形式
- 通过
props
属性向子组件传函数的时候 用bind
的形式
class App extends React.Component{
constructor(){
super()
// 因为我们要向子组件传值 ,所以父组件需要有自己的 state,这样比较接近开发的场景
this.state = {
app_num:10
}
// DOM 事件 修改this
this.increase = this.increase.bind(this)
}
render(){
let {app_num} = this.state
return(<div>
<h1>父组件</h1>
<button onClick={()=>{
this.increase(100)
}}>父组件-btn</button>
<Child num = {app_num} add = {this.increase.bind(this)} />
</div>)
}
// ***************自定义函数
// 点击事件
increase(a){
this.setState({
app_num:a
})
}
}
2.子组件的使用
1.子组件使用的时候比必须包裹一层箭头函数
class Child extends React.Component{
render(){
return(<div>
<h2>子组件 ---{this.props.num}</h2>
<button onClick={()=>this.props.add(999)}> 子组件 -btn </button>
</div>)
}
}
3. 父组件使用箭头函数
1.子组件并不需要改变,还是原来的写法就行
<Child num = {app_num} add = {()=>{this.increase(666)}} />
网友评论