我想在数组中显示一定数量的项目,当用户点击时,例如"显示下一个"数组的下五个项目将是可见的,如项目6-10,其中项目0-5将被隐藏,例如应始终只有五个项目可见。我怎样才能做到这一点?
我尝试了以下坚果但没有成功(请参阅JSFIDDLE此处)
class Cars extends React.Component{
constructor(){
super()
this.state = {
limit: 5,
cars: ["Audi", "Alfa Romeo", "BMW", "Citroen", "Dacia", "Ford", "Mercedes", "Peugeot", "Porsche", "VW"]
}
}
showPreviousCars() {
// show previous 5 items
}
showNextCars(){
this.setState({
limit: this.state.limit + 5
})
}
render(){
let cars = this.state.cars.slice(0,this.state.limit);
return(
<div className="car-wrapper">
<ul>
<li><a onClick={this.showPreviousCars.bind(this)}>Previous 5</a></li>
{cars.map((car, i) => {
return(
<li key={i}>{car}</li>
)
})}
<li><a onClick={this.showNextCars.bind(this)}>Next 5</a></li>
</ul>
</div>
)
}
}
欢迎任何建议!
答案 0 :(得分:3)
您可以使用Array.prototype.slice
(查看文档here了解要传递的参数)来处理数组的一部分:
cars.slice(this.state.limit, this.state.limit + 5).map(...)
编辑:两件事:
slice(this.state.limit - 5, this.state.limit)
showNextCars
功能,以确保不会超出阵列范围答案 1 :(得分:1)
使用偏移和限制
class Cars extends React.Component{
constructor(props){
super(props)
this.state = {
limit: 5,
offset:0,
cars: ["Audi", "Alfa Romeo", "BMW", "Citroen", "Dacia", "Ford", "Mercedes", "Peugeot", "Porsche", "VW"]
}
}
showPreviousCars() {
// show previous 5 items
}
showNextCars(){
this.setState({
offset:this.state.limit
limit: this.state.limit + 5,
})
}
render(){
let cars = this.state.cars.slice(this.state.offset,this.state.limit);
return(
<div className="car-wrapper">
<ul>
<li><a onClick={this.showPreviousCars.bind(this)}>Previous 5</a></li>
{cars.map((car, i) => {
return(
<li key={i}>{car}</li>
)
})}
<li><a onClick={this.showNextCars.bind(this)}>Next 5</a></li>
</ul>
</div>
)
}
}