在 React 中将 JSX 元素连接成一个数组

在 React 中将 JSX 元素连接成一个数组:

  1. 初始化一个空数组。
  2. 使用 push() 方法将 JSX 元素推送到数组中。
  3. 将最外层 JSX 元素上的 key 属性设置为唯一值。
export default function App() {
  const fruits = [];

  fruits.push(<div key="apple">Apple</div>);
  fruits.push(<div key="banana">Banana</div>);
  fruits.push(<div key="kiwi">Kiwi</div>);

  // 👇️ or if you have an array of strings
  const names = ['Alice', 'Bob', 'Carl'];

  const namesJsx = [];

  names.forEach((name, index) => {
    namesJsx.push(
      <div key={index}>
        <h2>{name}</h2>
        <hr />
      </div>,
    );
  });

  return (
    <div>
      <div>{fruits}</div>

      <br />

      <div>{namesJsx}</div>
    </div>
  );
}

第一个示例将 JSX 元素压入一个数组,然后渲染该元素数组。

我们必须将每个元素的 key 属性设置为唯一值。

const fruits = [];

fruits.push(<div key="apple">Apple</div>);
fruits.push(<div key="banana">Banana</div>);
fruits.push(<div key="kiwi">Kiwi</div>);

出于性能原因,React 在内部使用 key 道具。 它帮助库确保只重新呈现已更改的数组元素。

第二个示例展示了如何使用 forEach() 方法遍历一个字符串数组,并在每次迭代时将一个 JSX 元素推送到一个新数组中。

const names = ['Alice', 'Bob', 'Carl'];

const namesJsx = [];

names.forEach((name, index) => {
  namesJsx.push(
    <div key={index}>
      <h2>{name}</h2>
      <hr />
    </div>,
  );
});

当您需要为数组中的每个元素调用一个函数时,可以使用 Array.forEach 方法。

但是,forEach() 不能用于直接在 JSX 代码中遍历数组。

forEach() 方法使用数组中的每个元素调用提供的函数,但返回 undefined

直接在我们的 JSX 代码中使用它是没有意义的,因为我们需要返回 JSX 元素而不是未定义的。

我们可以使用 forEach() 方法来:

  1. 遍历一个数组。
  2. 将 JSX 元素推送到一个新数组中。
  3. 渲染 JSX 元素。
export default function App() {
  const names = ['Alice', 'Bob', 'Carl'];

  const namesJsx = [];

  names.forEach((name, index) => {
    namesJsx.push(
      <div key={index}>
        <h2>{name}</h2>
        <hr />
      </div>,
    );
  });

  return (
    <div>
      <div>{namesJsx}</div>
    </div>
  );
}