<Parent>
<Child config = {toggle: funciton(){console.log(this)}}></Child>
</Parent>
在子组件里this.props.config.toggle()
,这时在父组件里的this并不指向父组件本身,假如改成this.props.config.toggle.bind(this)()
,这时的this指向子组件。那应该怎么让这个this指向父组件呢。
<Parent>
<Child config = {toggle: funciton(){console.log(this)}}></Child>
</Parent>
在子组件里this.props.config.toggle()
,这时在父组件里的this并不指向父组件本身,假如改成this.props.config.toggle.bind(this)()
,这时的this指向子组件。那应该怎么让这个this指向父组件呢。
在父组件里绑定函数的this
。
class Parent extends React.Component {
toggle = () => {
console.log(this)
}
render() {
return <Child config = {toggle: this.toggle}></Child>
}
}
10 回答11.1k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
3 回答5.1k 阅读✓ 已解决
3 回答1.8k 阅读✓ 已解决
4 回答2.4k 阅读✓ 已解决
方法一:可以考虑把父组件的this传给子组件,bind的时候用传递的这个值;
方法二:使用箭头函数
子组件使用
this.props.config.toggle()
调用。