Javascript 在 .map 函数中使用 react props
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37155677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using react props in .map function
提问by Paran0a
Let's say I have the following render function on one of my components.
From the parent element I have passed a changeTid
prop function.
假设我在我的一个组件上具有以下渲染功能。从父元素我传递了一个changeTid
prop 函数。
Parent:
家长:
<RequestsList data={this.state.data} changeTid={this.changeTid} />
Child:
孩子:
(I'm using ES6 classes)
(我正在使用 ES6 类)
render() {
var RequestNodes = this.props.data.map(function(request) {
return (
<Request
key={request.TID}
changeTid={this.props.changeTid}
/>
);
});
return (
<div className="list-group">{RequestNodes}</div>
);
}
I can't use this.props.changeTid
in my map function as this
is not referencing what I wan't. Where do I bind it so I can access my props
?
我不能this.props.changeTid
在我的地图函数中使用,因为this
没有引用我不需要的东西。我在哪里绑定它以便我可以访问我的props
?
回答by Alexander T.
You can set this
for .map
callback through second argument
您可以设置this
为.map
通过第二个参数回调
var RequestNodes = this.props.data.map(function(request) {
/// ...
}, this);
or you can use arrow functionwhich does not have own this
, and this
inside it refers to enclosing context
或者你可以使用没有自己的箭头函数this
,this
在它里面指的是封闭的上下文
var RequestNodes = this.props.data.map((request) => {
/// ...
});
回答by Mauricio Poppe
If you're using ES6 you can use arrow functionswhich doesn't bind its own this
如果您使用的是 ES6,您可以使用不绑定自己的箭头函数this
var RequestNodes = this.props.data.map(request => {
return (
<Request
key={request.TID}
changeTid={this.props.changeTid}
/>
);
});