Kob*_*bek 8 javascript dictionary this reactjs
这是我之前的问题的一个跟进,但如果我在其中有一个映射,我如何在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>
);
}
Run Code Online (Sandbox Code Playgroud)
无论我尝试什么,我总是得到"this.getItemInfo()不是一个函数".
我做了console.log对this我的内部map()功能,这是逸岸指的Window对象,但我似乎无法找到一种方法来改变这种状况.
我累了:
getItemInfo为函数getItemInfo(){..}this作为第二个参数传递给我的map函数this.getItemInfo = this.getItemInfo.bind(this)react的组件构造函数.bind(this)后getItemInfo(item)还有其他几件事......
没有用.我对JavaScript的this参考相当新,我似乎无法弄明白.
我在这里阅读了一些与使用内部相关的答案,render()但它们似乎都不适合我.
Nai*_*han 17
collection.map(function (item) {
return <div> {item.Name} {this.getItemInfo(item)} </div>
})
Run Code Online (Sandbox Code Playgroud)
因此,this您的内部范围function(item)不是您的React组件的范围.
如果您使用箭头功能() => {...}而不是function() {...}您将有权访问thisReact.Component.
试试这个
collection.map((item) => (
<div> {item.Name} {this.getItemInfo.call(this, item)} </div>
))
Run Code Online (Sandbox Code Playgroud)
要阅读有关thisjavascript 范围的更多信息,请参阅此处:http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/
要阅读有关箭头功能和范围的信息this,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions的 "无单独"部分.