javascript - 在组件中反应调用函数,但函数失去了 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>
解决方案
那是因为, this 指的是被调用者的范围,因此并不像您期望的那样指代状态。在构造函数中将方法绑定到 this 或使用箭头函数。
toggle = () => {
console.log(this.state);
this.setState({
showModal: !this.state.showModal
});
};
推荐阅读
- visual-studio-code - 如何防止在 VSCode 中修剪尾随空白?
- php - 如何向用户发送非常长的表单
- json - 如何在 json 数据上编写 postgres 查询以检查特定条件
- django - 链接表的 Django 视图
- docker - 连接到 VPN 后 docker DNS 配置未更新
- r - 在 R 中按类别预测每周交易量
- git - 每次提交多个 Jenkins 构建
- javascript - 将 URL 输入转换为图像
- python - “import pyPDF2”导致“ModuleNotFoundError”
- visual-studio - 让 Visual Studio 使用 VS 代码快捷键/键绑定