<分区>
这是我之前问题的后续问题,但是如果我在 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()
中使用它相关的答案,但它们似乎都不适合我。