2

我在我的项目中使用React JSAnt Design

问题

我正在创建虚拟 DOM 元素。它有Popover在里面Button,然后点击那个显示Modal

它显示错误Cannot read property 'setState' of undefined

JS代码

content = (
  <div className="RecurringPopover"> 
    <button onClick={this.showModal}> Show Modal </button> 
  </div>
);

StackBlitz上的完整代码

4

2 回答 2

1

您需要将该方法绑定到适当的范围:

content = (
  <div className="RecurringPopover"> 
    <button onClick={this.showModal.bind(this)}> Show Modal </button> 
  </div>
);
于 2018-02-23T12:12:18.787 回答
0

添加你的构造函数

 constructor(props) {
    super(props);
    this.showModal = this.showModal.bind(this)
    this.state = {
        // hereyour state
    };
}

或者

onClick={this.showModal.bind(this)}

要关闭或打开模式,您可以这样做

 showModal() {
    this.setState({
        modal: !this.state.modal
    });
}
于 2018-02-23T12:14:47.130 回答