在react的子组件中,如何获取父组件的this

<Parent>
    <Child config = {toggle: funciton(){console.log(this)}}></Child>
</Parent>

在子组件里this.props.config.toggle(),这时在父组件里的this并不指向父组件本身,假如改成this.props.config.toggle.bind(this)(),这时的this指向子组件。那应该怎么让这个this指向父组件呢。

阅读 6.6k
3 个回答

方法一:可以考虑把父组件的this传给子组件,bind的时候用传递的这个值;
方法二:使用箭头函数

class Parent extends React.Component {
    toggle = () => {
        console.log(this)
    }
    render() {
        return <Child config = {toggle: this.toggle}></Child>
    }
}

子组件使用this.props.config.toggle()调用。

在父组件里绑定函数的this

class Parent extends React.Component {
    toggle = () => {
        console.log(this)
    }
    render() {
        return <Child config = {toggle: this.toggle}></Child>
    }
}
新手上路,请多包涵

你可以使用继承, 子组件继承一个父组件, 此时子组件中就有父组件的属性和方法了

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