在 React 中将 JSX 元素连接成一个数组
Concatenate JSX elements into an Array in React
在 React 中将 JSX 元素连接成一个数组:
- 初始化一个空数组。
- 使用
push()
方法将 JSX 元素推送到数组中。 - 将
key
最外层 JSX 元素上的 prop 设置为唯一值。
应用程序.js
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
每个元素的 prop 设置为唯一值。
应用程序.js
const fruits = []; fruits.push(<div key="apple">Apple</div>); fruits.push(<div key="banana">Banana</div>); fruits.push(<div key="kiwi">Kiwi</div>);
key
出于性能原因,React 在内部使用该prop。它帮助库确保只重新呈现已更改的数组元素。
The second example shows how to iterate over an array of strings using the
forEach()
method and push a JSX element into a new array on each iteration.
App.js
const names = ['Alice', 'Bob', 'Carl']; const namesJsx = []; names.forEach((name, index) => { namesJsx.push( <div key={index}> <h2>{name}</h2> <hr /> </div>, ); });
The
Array.forEach
method can be used when you need to call a function for every element in an
array.
However,
forEach()
can’t be used to iterate over an array directly in your JSX code.The forEach()
method calls the provided function with each element in the
array but returns undefined
.
Using it directly in our JSX code wouldn’t make sense because we need to return
JSX elements and not undefined
.
You can use the forEach()
method to:
- Iterate over an array.
- Push JSX elements into a new array.
- Render the JSX elements.
App.js
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> ); }