所以,我还是 Reactjs 的初学者。我想根据来自 api 响应的数字在“.menu”div 中复制此“a”标签。
<div className="menu">
<a onClick={this.targetValue} href="#">1</a>
</div>
如果我从这样的 api 响应返回的数量
quantity: "3"
我想像这样复制“a”标签3次,并根据其数量更改文本内容
<div className="menu">
<a onClick={this.targetValue} href="#">1</a>
<a onClick={this.targetValue} href="#">2</a>
<a onClick={this.targetValue} href="#">3</a>
</div>
最佳答案
请记住,JSX 仍然是 JavaScript(顶部有一些位)。所以如果你想重复某件事,你可以循环播放。 JS 中迭代的方法有很多种,这里介绍几种。
For loop :
render() {
const links = [];
// Loop the number of times your API dictates
for (step = 0; step < 5; step++) {
// Create a link for each number
// You want to add the `key` property to each child when iterating
links.push(<a key={step} onClick={this.targetValue} href="#">{step + 1}</a>)
}
return (
<div className="menu">
{links} {/* render your links */}
</div>
)
}
render() {
return (
<div className="menu">
{Array(5).fill(null).map((_, index) => (
<a key={index} onClick={this.targetValue} href="#">{index + 1}</a>
))}
</div>
)
}
Lodash [_.times}( https://lodash.com/docs/4.17.5#times ):
render() {
return (
<div className="menu">
{_.times(5, i => (
<a onClick={this.targetValue} key={i} href="#">{i + 1}</a>
))}
</div>
)
}
更新:添加了keys
和lodash,感谢@JoshKelly
关于reactjs - 重复的 "a"标签取决于我从 api 响应中获得的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52265748/