我想迭代一个数组并在每次单击按钮时显示数组中的每个元素。
到目前为止我有这个:
{this.state.users.map(function(user, index){
return <p key={ index }>{user.name} </p>;
}, this)}
这会在屏幕上依次显示每个用户的名称。 我该如何做到这一点,以便它只显示用户[0],然后移动到用户[1],甚至更好,单击删除位置用户[0]的用户,然后一个新人位于位置用户[0],然后如果数组为空,它显示文本“没有更多用户” 我知道如何从数组等中删除元素,这只是在 React 土地上一次显示一个元素,这是我做不到的
最佳答案
根据我对您问题的理解,您可能正在尝试实现这一目标 -
let users = [{
name: "abcd"
}, {
name: "xyz"
}, {
name: "temp"
}];
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
activeIndex: 0
};
}
tick =() => {
let activeIndex = this.state.activeIndex;
if (activeIndex == this.props.users.length -1){
activeIndex = 0;
} else {
activeIndex++;
}
this.setState({
activeIndex
});
}
render() {
return (
< ul className = "list-group" >
< li className = "list-group-item" >
{this.props.users[this.state.activeIndex].name}
< button className = "btn btn-default" onClick={this.tick} >
show Next
< /button>
</li >
< /ul>
);
}
}
ReactDOM.render(
< Example users = {users}/ > ,
document.getElementById('test')
);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="test">
</div>
关于javascript - 在React中显示数组数据onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40397257/