在 React JS 中按下按钮后,如何使数组元素逐一出现?

How to make an array element appear on by one after the button is pressed in 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"));

上面的代码只是一次打印所有数组元素。单击按钮后如何使它们一个接一个地出现(单击一次 - 显示 arr[0],第二次单击 - 显示 arr[1] 等?

添加一个新状态来更新索引,并让按钮调用该函数。然后调用另一个函数,将数组元素切片到索引,map 在该数组和 return 一些 JSX 上。

const { useState } = React;

function Example() {

 const [arr, setArr] = useState(['bmw', 'mercedes', 'audi']);

 // Add a new state for the index
 const [index, setIndex] = useState(0);

  // Click the button - update the index
  function addElement(arr) {
    setIndex(index + 1);
  }

  // Return some JSX by slicing the array up
  // to the index, and then `map` over that array
  // and return some divs
  function getElements(arr, index) {
    return arr.slice(0, index).map(el => {
      return <div>{el}</div>;
    });
  }
  
  return (
    <div>
      <button onClick={addElement}>Add item</button>
      {getElements(arr, index)}
    </div>
  );

}

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

您可以使用代表 index 的状态和 slice 方法:

const [index, setIndex] = useState(0);

return (
<button onClick={() => setIndex(prevIndex => prevIndex + 1)}>Click Me</button>
{array.slice(0, index).map(x => <p>{x} </p>)}
);