javascript - map 中的 ReactJS onClick 处理程序返回未定义

标签 javascript reactjs

我想在<a>上添加一个处理程序在map :

我的简单功能:

getFacilities = (e) => {
    console.log(e)
}

渲染中:

    const items = this.state.data;
    let result = items.map(function(value, i){
        return (
            <List.Item key={i}>
               <a onClick={this.getFacilities}>{value.user.name}</a>
            </List.Item>
        );
    });

TypeError: Cannot read property 'getFacilities' of undefined

有很多主题都出现此错误,几乎所有主题都使用此作为解决方案:

我将其添加到constructor

this.getFacilities = this.getFacilities.bind(this)

但它在我的情况下不起作用,并且仍然返回相同的错误。很简单,困惑无法弄清楚我错过了什么,我做错了什么。

最佳答案

需要注意的关键是普通函数表达式和新的 ES6 箭头函数之间的区别。简而言之:与函数表达式不同,箭头函数不维护自己的 this (或 arguments) - 它们从外部词法环境借用它。

"An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords. Arrow function expressions are ill suited as methods, and they cannot be used as constructors."

因此,当您在 map 回调中引用 this 时,this 并不引用该类。

因此1)将函数表达式更改为箭头函数:

let result = items.map((value, i) => {
  return (
    <List.Item key={i}>
      <a onClick={this.getFacilities}>{value.user.name}</a>
    </List.Item>
  );
});

2) 由于您在类方法中使用了箭头函数,因此您可以将其删除,因为仅当您使用标准类方法定义而不是类字段时才需要这样做。

this.getFacilities = this.getFacilities.bind(this);

但是有一些证据表明类字段(使用箭头函数),例如这些 are worse than using standard class method format ,因此您最好将绑定(bind)保留在构造函数中并使用您传递的函数的标准格式:

getFacilities(e) {
  console.log(e)
}

这是需要牢记的事情。

<小时/>

PS,来自该链接:

"It is unnecessary to do that to every function. This is just as bad as autobinding (on a class). You only need to bind functions that you pass around. e.g. onClick={this.doSomething}. Or fetch.then(this.handleDone) — Dan Abramov‏"

关于javascript - map 中的 ReactJS onClick 处理程序返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59154746/

相关文章:

javascript - Angular/ ionic /Javascript : Can't get drop-down filter to work as check-box

reactjs - 将输入文本从组件传递回父级

javascript - ReactJS - 推送到 promise 之外的列表

reactjs - Storybook 中缺少 MaterialUI 表 Prop

javascript - Vue中满足一定条件的嵌套值过滤数组

javascript - SVG 动画在调整大小后非常滞后(专家)?

Javascript 图像面板,图像大小相同

javascript - 通过 db.transaction 函数传递参数

javascript - 渲染 div 的 map 及其标题

reactjs - Material-UI:如何去除 InputLabel 的转换?