两个组件:
父组件:
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值?
用箭头函数定义方法
或者在constructor绑定