<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.7k 阅读
2 回答3.2k 阅读✓ 已解决
2 回答4.3k 阅读✓ 已解决
3 回答1.9k 阅读✓ 已解决
2 回答1.7k 阅读✓ 已解决
4 回答2.5k 阅读✓ 已解决
5 回答3.9k 阅读
方法一:可以考虑把父组件的this传给子组件,bind的时候用传递的这个值;
方法二:使用箭头函数
子组件使用
this.props.config.toggle()
调用。