react里的this指向问题

两个组件:

父组件:

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值?

阅读 2.8k
5 个回答

用箭头函数定义方法

setPage= () => {...}

或者在constructor绑定

constructor(props) {
    super(props);
    this.state = {
        ...
    };
    this.setPage = this.setPage.bind(this);
}
setPage = {()=>this.setPage()}

setPage = {this.setPage.bind(this)}
or
setPage = {()=>{this.setPage()}}

通过 bind 绑定 this

constructor(props){
    super(props);
    this.state = {
        currentPage:0
    };
    this.setPage = this.setPage.bind(this);
}

把<App setPage={this.setPage} /> 改成<App setPage={this.setPage.bind(this)} /> 试试。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题