React 遍历生成 5 个不同颜色 DIV 块,并渲染不同数据
你可以使用 React 的 map 方法来遍历生成 5 个不同颜色的 div 块,并在每个 div 块中遍历渲染不同的数据。如果某个 div 块没有数据,你可以使用一个空字符串作为渲染的数据。
下面是一个示例代码:
import React from 'react';
const colors = ['red', 'blue', 'green', 'yellow', 'orange'];
const data = ['Data 1', 'Data 2', 'Data 3', '', 'Data 5'];
const App = () => {
return (
<div>
{colors.map((color, index) => (
<div key={index} style={{ backgroundColor: color }}>
{data[index]}
</div>
))}
</div>
);
};
export default App;
在上面的示例中,我们定义了一个颜色数组 colors 和一个数据数组 data。然后使用 map 方法遍历 colors 数组,在每个循环中生成一个 div 块,并设置背景颜色为当前循环的颜色。同时,使用 data[index] 来渲染对应的数据,如果数据为空字符串,则会渲染一个空的 div 块。
注意要给每个生成的 div 块设置一个唯一的 key 属性,这里我们使用 index 作为 key 值。这有助于 React识别每个元素的变化,提高性能和优化渲染。
原文地址: https://www.cveoy.top/t/topic/qmz9 著作权归作者所有。请勿转载和采集!