我有这个功能:
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> );
}
我得到:
未捕获的TypeError:无法读取未定义的属性'deleteTag' 在onClick(bundle.js:46275) 在Object.ReactErrorUtils.invokeGuardedCallback(bundle.js:4594) 在executeDispatch(bundle.js:4394) 在Object.executeDispatchesInOrder(bundle.js:4417) 在executeDispatchesAndRelease(bundle.js:3847) 在executeDispatchesAndReleaseTopLevel(bundle.js:3858) 在Array.forEach() 在forEachAccumulated(bundle.js:4694) 在Object.processEventQueue(bundle.js:4063) 在runEventQueueInBatch(bundle.js:4723)
我确定这很愚蠢,但我无法弄清楚!
答案 0 :(得分:3)
那是因为赋予map
的功能未绑定。您可以改用箭头功能,而this
将是您所期望的。
const renderTags = this.state.data.tags.map((tag,i) => {
return <span key={i} onClick={() => this.deleteTag()}>{tag} </span>
});