两个组件:父组件:constructor(props){ super(props); this.state = { currentPage:0 }}setPage(num){ console.log(this); //得出的是子组件 this.setState({ //提示'setState'不是一个方法 currentPage:num }) }render(){ return( <div> <App setPage = {this.setPage} /> </div> )}子组件:clickFuc(index) { this.setState({ currentIndex: index },()=>{ this.props.setPage(index); }) } render(){ return ( <div onClick={this.clickFuc.bind(this,index)}></div> ) }问题:这里的this还是子组件,没有指向父组件,该如何达到通过子组件来改变父组件的state值?
5 回答
慕的地10843
TA贡献1785条经验 获得超8个赞
用箭头函数定义方法
setPage= () => {...}
或者在constructor绑定
constructor(props) {
super(props);
this.state = {
...
};
this.setPage = this.setPage.bind(this);
}
红糖糍粑
TA贡献1815条经验 获得超6个赞
通过 bind 绑定 this
constructor(props){
super(props);
this.state = {
currentPage:0
};
this.setPage = this.setPage.bind(this);
}
函数式编程
TA贡献1807条经验 获得超9个赞
添加回答
举报
0/150
提交
取消
