Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

在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指向父组件呢。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...