javascript - 在 React render() 的 map() 函数中调用函数

标签 javascript reactjs dictionary this

<分区>

这是我之前问题的后续问题,但是如果我在 React 的 render() 方法中有一个映射,我该如何调用函数。

示例(此代码在扩展 React.Component 的类中):

getItemInfo(item){
  return `${item.Something} ${item.SomethingElse}`
}

render() {

return (
 <div className="someDiv">
    {
      collection.map(function (item) {
        return <div> {item.Name} {this.getItemInfo(item)} </div>
    })
  }
 </div>
);

}

无论我尝试什么,我总是得到“this.getItemInfo() 不是一个函数”。

我在 map() 函数中的 this 上做了一个 console.log,它实际上是指 Window 对象,但我似乎找不到改变它的方法。

我累了:

  • getItemInfo 定义为函数 getItemInfo(){..}
  • this 作为我的 map 函数的第二个参数传递
  • 在 React 的组件构造函数中调用 this.getItemInfo = this.getItemInfo.bind(this)
  • getItemInfo(item) 之后调用 .bind(this)

还有一些其他的东西....

都没有用。我对 JavaScript 的 this 引用相当陌生,我似乎无法理解。

我在这里阅读了一些与在 render() 中使用它相关的答案,但它们似乎都不适合我。

最佳答案

collection.map(function (item) {
    return <div> {item.Name} {this.getItemInfo(item)} </div>
})

因此,function(item) 中的 this 的范围不是 React Component 的范围。

如果您使用箭头函数 () => {...} 而不是 function() {...} 您将可以访问 this 的 React.Component。

试试这个

collection.map((item) => (
   <div> {item.Name} {this.getItemInfo.call(this, item)} </div>
))

要阅读有关 javascript 中 this 作用域的更多信息,您可以在此处阅读:http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/

要了解箭头函数和 this 的作用域,请参阅“No separate this "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions 的部分

关于javascript - 在 React render() 的 map() 函数中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46969246/

相关文章:

javascript - React js 重新渲染表单中的大量组件

reactjs - 如何在 react 测试库中获得代码覆盖率

c# - 字典和锁 C# 的奇怪问题

macos - 如何挂接 OS X 字典

javascript - 将 "extra"参数传递给存储在变量中的函数 - Javascript

javascript - 选择后动态隐藏选项组

reactjs - react 路由器 : Add types to NavLink isActive() function

javascript - JSON 对象的 Typescript 模型类

javascript - 如何为表中的多个数据创建 AJAX POST 按钮?

c# - 如何使用 LINQ 将数组转换为字典