首页 > 解决方案 > 在组件中反应调用函数,但函数失去了 this 的定义

问题描述

我有这段代码,由于某种原因,当调用切换时,控制台给出了“this.state”的未定义。不太清楚它发生了什么。

// Toggles the modal to open or close depending on current state
  toggle() {
    console.log(this.state);
    this.setState({
      showModal: !this.state.showModal
    });
  };

向下渲染

<Modal isOpen={this.state.showModal} toggle={this.toggle}>
  <ModalHeader toggle={this.toggle}>Modal title</ModalHeader>
  <ModalBody>
    Lorem ipsum dolor sit amet
  </ModalBody>
  <ModalFooter>
    <Button color="primary" onClick={this.toggle}>Save</Button>
    <Button color="secondary" onClick={this.toggle}>Cancel</Button>
  </ModalFooter>
</Modal>

标签: javascriptreactjsreactstrap

解决方案


那是因为, this 指的是被调用者的范围,因此并不像您期望的那样指代状态。在构造函数中将方法绑定到 this 或使用箭头函数。

toggle = () => {
  console.log(this.state);
  this.setState({
    showModal: !this.state.showModal
  });
};

推荐阅读