Javascript 在react onclick中循环通过数组
我有一个对象数组。如何在单击时循环此数组Javascript 在react onclick中循环通过数组,javascript,reactjs,loops,Javascript,Reactjs,Loops,我有一个对象数组。如何在单击时循环此数组 test = ['a', 'b', 'c', 'd'] {this.state.test.map(function(i){ return <span> {i} </span> })} test=['a','b','c','d'] {this.state.test.map(函数(i)){ 返回{i} })} 我通常会像这样在react中循环,但这会一次打印出来。如何在页面上显示“a”,然后在下次单击时显示“b”,
test = ['a', 'b', 'c', 'd']
{this.state.test.map(function(i){
return <span> {i} </span>
})}
test=['a','b','c','d']
{this.state.test.map(函数(i)){
返回{i}
})}
我通常会像这样在react中循环,但这会一次打印出来。如何在页面上显示“a”,然后在下次单击时显示“b”,直到数组结束
我需要一个函数,它可以告诉我在数组中的位置,并在适当的时候在页面上显示它您可以实现一个计数器变量,并使用
数组#切片
显示测试
数组中指定数量的元素
import React from "react";
export default class Hello extends React.Component {
state = {
test: ["a", "b", "c", "d"],
index: 0
};
handleClick = () => {
let i = this.state.index < this.state.test.length ? this.state.index += 1 : 0;
this.setState({ index: i });
};
render() {
return (
<div>
{this.state.test.slice(0, this.state.index).map(v => {
return (
<span>{v}</span>
);
})}
<button onClick={this.handleClick}>Click</button>
</div>
);
}
}
以及Span.js
组件:
<span hidden={this.props.hidden}>
{this.props.v}
</span>
{this.props.v}
首先将初始索引设置为您的状态,然后将该索引用作span中的索引数组。接下来做一些函数来处理增量,简单地说如下
const switchNinjaHandler = () => {
let looper = ++this.state.index % this.state.test.length;
setState({
...personsState, // WE SHOULD ALWAYS GIVE THE EXCACT INITIAL STATE VALUE, THIS IS WHERE SPREAD COMING HANDY
this.index : looper,
});
显示
return ( <div> {this.state.test[this.index]} </div> )
return({this.state.test[this.index]})
return ( <div> {this.state.test[this.index]} </div> )