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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:59:19  来源:igfitidea点击:

Using react props in .map function

javascriptreactjsecmascript-6

提问by Paran0a

Let's say I have the following render function on one of my components. From the parent element I have passed a changeTidprop function.

假设我在我的一个组件上具有以下渲染功能。从父元素我传递了一个changeTidprop 函数。

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.changeTidin my map function as thisis 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 thisfor .mapcallback 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 thisinside it refers to enclosing context

或者你可以使用没有自己的箭头函数thisthis在它里面指的是封闭的上下文

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}
    />
  );
});