在React中使用map()传递附加参数
Passing Additional Arguments with map() in React
我目前正在映射一个像这样的道具:
renderList(item) {
return(
</div>
shows up
</div>
)
}
render() {
return(
<div>
{this.props.items.map(this.renderList)}
</div>
);
}
}
我想传递另一个道具
this.props.completed
我想做的事情的简化版本
renderList(item, completed) {
return(
</div>
shows up
</div>
)
}
render() {
return(
<div>
{this.props.items.map(this.renderList(this.props.items, this.props.completed)}
</div>
);
}
}
是否可以传递另一个道具与这个地图功能?
有(至少)3种方法可以做到这一点。最简单的方法是将renderList
绑定到组件实例,并在其中引用this.props.completed
:
constructor (props) {
super(props);
// it's more efficient to bind your functions once in the constructor than
// doing so on every render
this.renderList = this.renderList.bind(this);
}
renderList(item) {
const completed = this.props.completed;
return(
<div>
shows up
</div>
)
}
render() {
return(
<div>
{this.props.items.map(this.renderList)}
</div>
);
}
另一个选择是使用闭包将属性传递给函数:
renderList(completed, item) {
return(
<div>
shows up
</div>
)
}
render() {
const completed = this.props.completed;
const renderList = this.renderList;
return(
<div>
{this.props.items.map(function (item) {
return renderList(completed, item);
})}
</div>
);
}
第三种选择是将属性绑定到map()
回调。
renderList(completed, item) {
return(
<div>
shows up
</div>
)
}
render() {
return(
<div>
{this.props.items.map(this.renderList.bind(this, this.props.completed))}
</div>
);
}
相关文章:
- 如何在react路由器的组件中使用参数
- React 路由器和任意查询参数:页面在加载时无意中刷新
- 如何使用React Router在Route Handler上获取参数
- 如何使用react路由器在重定向时传递参数
- React路由器参数化路由:SyntaxError:预期表达式,得到'<'
- React-具有参数的同一类中的事件
- React native:如何将参数传递给手势响应程序回调
- 一个组件如何在 React 中将自己作为参数传递
- 当函数绑定在构造函数中时,如何在 ES6 React 中向事件处理程序添加参数
- 通过快速路由将参数传递给 React
- React 服务器端渲染 - 如何使用传入的 :p roductId 参数从服务器渲染
- 在 React Router 中,我如何路由到 2 个具有不同参数的相似 url
- 将参数传递给React Native中的组件
- 这个问题的原因是什么;无法转换org.json.JSONArray类型的参数“”;在react原生android中
- React-router path参数不起作用
- 从其他组件获取参数[React JS]
- React Link onClick没有利用当前参数
- Redux中的React Router路由参数
- react-router是如何通过props传递参数给其他组件的?
- React-router没有填充参数