在React JS中按下按钮后,如何使数组元素出现在一个上?
import ReactDOM from 'react-dom';
import React, {useState} from 'react';
function App() {
const [arr, setArr] = useState(["bmw", "mercedes", "audi"]);
let result;
let i = 0;
function Add() {
????
}
return(
<div>
<button onClick={Add}>Add item</button>
<div>{arr.map(x => <p>{x}</p>)}</div>
</div>
)
}
ReactDOM.render(<App />, document.getElementById("root"));
上面的该代码仅一次打印所有数组元素。单击按钮后,如何使'em逐一显示(一键显示-ARR [0],第二键单击-ARR [1]等等?
import ReactDOM from 'react-dom';
import React, {useState} from 'react';
function App() {
const [arr, setArr] = useState(["bmw", "mercedes", "audi"]);
let result;
let i = 0;
function Add() {
????
}
return(
<div>
<button onClick={Add}>Add item</button>
<div>{arr.map(x => <p>{x}</p>)}</div>
</div>
)
}
ReactDOM.render(<App />, document.getElementById("root"));
This code above just prints all the array elements at once. How do I make 'em appear one by one after clicking the button (one click - arr[0] is displayed, second click - arr[1] is displayed etc.?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
添加一个新状态以更新索引,并具有该功能的按钮调用。然后调用另一个将数组元素切割到索引的功能,
MAP
在该数组上并返回一些JSX。Add a new state to update the index, and have the button call that function. Then call another function that slices off the array elements up to the index,
map
over that array and return some JSX.您可以使用表示
index
和slice
方法的状态:You could use a state that represents
index
and theslice
method: