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

时间:2017-10-27 06:59:41

标签: 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()不是一个函数”。

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

我累了:

  • getItemInfo定义为函数getItemInfo(){..}
  • this作为第二个参数传递给我的地图功能
  • 在react的组件构造函数中调用this.getItemInfo = this.getItemInfo.bind(this)
  • .bind(this)
  • 之后致电getItemInfo(item)

还有其他一些事情......

没有用。我对JavaScript的this引用相当新,我似乎无法弄明白。

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

1 个答案:

答案 0 :(得分:12)

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

因此,thisfunction(item)的范围不是您的React组件的范围。

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

试试这个

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

要详细了解javascript中this的范围,请在此处阅读:http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/

要阅读this的箭头功能和范围,请参阅&#34;不要单独使用此功能 &#34; https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

的部分
相关问题