为了账号安全,请及时绑定邮箱和手机立即绑定

react里的this指向问题

react里的this指向问题

狐的传说 2019-03-12 10:12:34
两个组件:父组件: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);

}


查看完整回答
反对 回复 2019-03-15
?
holdtom

TA贡献1805条经验 获得超10个赞

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


查看完整回答
反对 回复 2019-03-15
?
炎炎设计

TA贡献1808条经验 获得超4个赞

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

查看完整回答
反对 回复 2019-03-15
?
红糖糍粑

TA贡献1815条经验 获得超6个赞

通过 bind 绑定 this


constructor(props){

    super(props);

    this.state = {

        currentPage:0

    };

    this.setPage = this.setPage.bind(this);

}


查看完整回答
反对 回复 2019-03-15
?
函数式编程

TA贡献1807条经验 获得超9个赞

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


查看完整回答
反对 回复 2019-03-15
  • 5 回答
  • 0 关注
  • 538 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号