【发布时间】: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