gpt4 book ai didi

javascript - 尽管已绑定(bind),但在 onClick 处未定义 React 函数?

转载 作者:行者123 更新时间:2023-11-30 11:17:06 25 4
gpt4 key购买 nike

我有这个功能:

  deleteTag() {
// this.data.tags.pop();
console.log("I will delete a tag");
}

我在构造函数中绑定(bind)它:

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> );
}

我得到:

Uncaught TypeError: Cannot read property 'deleteTag' of undefined at onClick (bundle.js:46275) at Object.ReactErrorUtils.invokeGuardedCallback (bundle.js:4594) at executeDispatch (bundle.js:4394) at Object.executeDispatchesInOrder (bundle.js:4417) at 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的函数没有绑定(bind)。您可以改用箭头函数,this 将是您所期望的。

const renderTags = this.state.data.tags.map((tag,i) => {
return <span key={i} onClick={() => this.deleteTag()}>{tag} </span>
});

关于javascript - 尽管已绑定(bind),但在 onClick 处未定义 React 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51135536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com