我有一个父组件,它将 onSomeAction
属性提供给子组件:
export default class myComponent extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="mycomponent">
<ChildComponent onSomeAction={this.doSomething} />
</div>
)
}
doSomething() {
console.log(this);
}
}
在子组件中,当单击某些内容时,我正在调用一个方法,该方法依次调用 onSomeAction
属性:
export default class ChildComponent extends Component {
render() {
return (
<div className="">
<a onClick={() => this.doIt()}>doIt</a>
</div>
)
}
doIt() {
const { onSomeAction } = this.props;
onSomeAction();
}
}
我看到的问题又出现在父组件中,this 上下文似乎已经丢失 - doSomething
方法中的 console.log
返回未定义。为什么是这样?我需要能够访问
父组件上下文。
最佳答案
您需要在父组件中设置上下文,可以使用 .bind
来完成
<ChildComponent onSomeAction={ this.doSomething.bind(this) } />
^^^^^^^^^^^^
关于reactjs - 从子组件调用时,父组件中的上下文丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35082607/