在React render()中的map()函数内部调用函数 [英] Calling functions inside a map() function in React render()
问题描述
这是我上一个问题的后续内容,但是,如果我内部有一个映射,该如何在React的render()方法中调用一个函数.
This is a follow up to my previous question, but how do I call a function inside React's render() method, if I have a map inside that.
示例(此代码在扩展React.Component
的类内):
Example (this code is inside a class that extends 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()不是函数".
No matter what I try I always end up getting "this.getItemInfo() is not a function".
我在map()
函数内的this
上做了一个console.log
,实际上是指Window对象,但是我似乎找不到改变它的方法.
I did a console.log
on this
inside my map()
function and it was infact refering to the Window object, but I can't seem to find a way to change that.
我很累:
- 将
getItemInfo
定义为函数getItemInfo(){..} - 将
this
作为第二个参数传递给我的地图函数 - 在react的组件构造函数中调用
this.getItemInfo = this.getItemInfo.bind(this)
- 在
getItemInfo(item)
之后呼叫.bind(this)
- defining
getItemInfo
as function getItemInfo(){..} - passing
this
as a second parameter to my map function - calling
this.getItemInfo = this.getItemInfo.bind(this)
in react's component constructor - calling
.bind(this)
aftergetItemInfo(item)
还有其他几件事......
And a couple other things....
没有工作.我对JavaScript的this
参考还很陌生,但似乎无法弄清楚.
None worked. I am fairly new to JavaScript's this
reference, and I cant seem to figure it out.
我在这里阅读了一些与在render()
中使用此方法有关的答案,但似乎没有一个对我有用.
I read some answers here related to using this inside render()
but none of them seemed to work for me.
推荐答案
collection.map(function (item) {
return <div> {item.Name} {this.getItemInfo(item)} </div>
})
因此,function(item)
中this
的范围不是React组件的范围.
So, the scope of this
inside your function(item)
is not the scope of your React Component.
如果使用箭头功能() => {...}
代替function() {...}
,则可以访问React.Component的this
.
If you use arrow function () => {...}
instead of function() {...}
you will have access to this
of React.Component.
尝试一下
collection.map((item) => (
<div> {item.Name} {this.getItemInfo.call(this, item)} </div>
))
要了解有关JavaScript中this
范围的更多信息,可以在这里阅读:
To read more about scope of this
in javascript, you can read here: http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/
要了解有关箭头功能和this
范围的信息,请参阅不单独列出此内容".
" https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions
To read about arrow functions and scope of this
, refer to "No separate this
" section of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
这篇关于在React render()中的map()函数内部调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!