在上下文状态下,我有一个HandlePopUp
函数和一个Visibility
布尔值。在构造函数中,我将Visibility = false
和HandlePopUp设置为以下内容。
HandlePopUp: () => {
//toggles Visibility to true and false. by default its set to false.
}
在另一个组件中,我试图像这样使用使用者:
export class OwnersHeader extends React.Component {
private localContext;
public componentDidMount() {
return <MyConsumer>
{(context) => {
return (
this.localContext = context
);
}}
</MyConsumer>;
}
public render() {
return (
<div>
<button onClick={this.localContext.HandlePopUp}>Open PopUp</button>
{ this.localContext.Visibility ? <PopUp /> : null }
</div>
);
}
}
我试图将上下文加载到局部变量中,然后使用它有条件地呈现PopUp
组件。但这会引发Cannot read property 'HandlePopUp' of undefined
错误。
给我留下了深刻的印象,将上下文存储在componentDidMount(在渲染之前触发)将允许我执行此操作。
我该如何解决?谢谢!