【问题标题】:Calling functions inside a map() function in React render() [duplicate]在 React render() 中调用 map() 函数中的函数 [重复]
【发布时间】:2018-04-08 17:12:42
【问题描述】:

这是我上一个问题的后续,但是如果我在 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() is not a function”。

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

我累了:

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

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

没有工作。我对 JavaScript 的 this 参考相当陌生,我似乎无法弄清楚。

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

【问题讨论】:

    标签: javascript reactjs dictionary this


    【解决方案1】:
    collection.map(function (item) {
        return <div> {item.Name} {this.getItemInfo(item)} </div>
    })
    

    因此,this 在您的 function(item) 中的范围不是您的 React 组件的范围。

    如果您使用箭头函数 () =&gt; {...} 而不是 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 的箭头功能和范围,请参阅“没有单独的 this "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions的部分

    【讨论】:

    • 嗯,这还是说 this.getItemInfo() 不是函数。我是否必须对我的函数声明做任何特别的事情才能让它工作
    • 嘿,我已经用this.getItemInfo.call(this, item) 更新了答案。如果在render()中使用this.func(),需要绑定。
    • 刚试过。我现在无法读取未定义的属性:(
    • 编辑:我设法让它工作。我有一个内部 .map(function) 也需要更改。谢谢你的详细回答:)
    猜你喜欢
    • 2019-08-28
    • 2016-09-06
    • 1970-01-01
    • 2015-02-14
    • 2016-10-23
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 2019-01-04
    相关资源
    最近更新 更多