首页 > 解决方案 > 尽管已绑定,但在 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)

我确定这很愚蠢,但我无法弄清楚!

标签: javascriptreactjsfunctionreact-redux

解决方案


那是因为给定的功能map没有绑定。您可以改用箭头函数,this这将是您所期望的。

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

推荐阅读