在.map函数中使用反应道具 [英] Using react props in .map function

查看:164
本文介绍了在.map函数中使用反应道具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在我的一个组件上有如下渲染功能。
从父元素我已经通过了一个 changeTid prop函数。



父级: / strong>

 < RequestsList data = {this.state.data} changeTid = {this.changeTid} /> 

孩子:



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

我不能使用 this.props.changeTid 在我的地图函数中这个没有引用我不知道的东西。我在哪里绑定,所以我可以访问我的道具

解决方案

您可以为 pre $ p $ var RequestNodes = this.props.data.map(function(request){
/// ...
},this);

或者您可以使用这个和这个的箭头功能的US / docs / Web / JavaScript / Reference / Functions / Arrow_functions / code>里面是指封闭上下文

  var RequestNodes = this.props.data.map((request) => {
/// ...
});


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.

Parent:

<RequestsList data={this.state.data} changeTid={this.changeTid} />

Child:

(I'm using ES6 classes)

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?

解决方案

You can set this for .map callback through second argument

var RequestNodes = this.props.data.map(function(request) {
   /// ...
}, this);

or you can use arrow function which does not have own this, and this inside it refers to enclosing context

var RequestNodes = this.props.data.map((request) => {
       /// ...
});

这篇关于在.map函数中使用反应道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆