javascript - 尽管已绑定,但在 onClick 处未定义 React 函数?
问题描述
我有这个功能:
deleteTag() {
// this.data.tags.pop();
console.log("I will delete a tag");
}
我在构造函数中绑定它:
this.deleteTag = this.deleteTag.bind(this);
但是当我尝试这样做时:
render() {
const renderTags = this.state.data.tags.map(function(tag,i){
return <span key={i} onClick={() => this.deleteTag()}>{tag} </span>
});
return ( <div> {renderTags} </div> );
}
我得到:
未捕获的类型错误:在 Object.executeDispatchesInOrder (bundle.js :4417) 在executeDispatchesAndRelease (bundle.js:3847) at executeDispatchesAndReleaseTopLevel (bundle.js:3858) at Array.forEach () at forEachAccumulated (bundle.js:4694) at Object.processEventQueue (bundle.js:4063) at runEventQueueInBatch ( bundle.js:4723)
我确定这很愚蠢,但我无法弄清楚!
解决方案
那是因为给定的功能map
没有绑定。您可以改用箭头函数,this
这将是您所期望的。
const renderTags = this.state.data.tags.map((tag,i) => {
return <span key={i} onClick={() => this.deleteTag()}>{tag} </span>
});
推荐阅读
- javascript - 无法在 Chart.js 中显示轴标签
- angular - 使用指令有条件地附加/删除文本
- django - 两个 Django 项目、一个 Postgresql 数据库和 Docker
- php - PHP - 如何获取多个复选框的值以及输入类型
- javascript - 绘制 Phaser 饼图的问题
- python - 打印带有分隔符的列表
- javascript - 如何在 react + firestore 中呈现异步数据?
- scala - 具有基础类型的类型参数 - Scala
- python - 在数据集 PYTHON 上使用正则表达式分隔
- vba - 最后将 Excel 工作表复制到另一个工作簿 (VBA)