在 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>
);
}
}
这个map函数可以传另一个prop吗?
有(至少)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>
);
}
我目前正在像这样映射道具:
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>
);
}
}
这个map函数可以传另一个prop吗?
有(至少)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>
);
}