{"title":"React 遍历生成 5 个不同颜色 div 块 - 完整示例代码","description":"使用 React 的 map() 方法遍历数组,并使用随机颜色来设置每个 div 的背景色。本文提供完整代码示例,帮助您轻松实现此功能。","keywords":"React, map(), 遍历, div, 不同颜色, 随机颜色, 背景色, 代码示例","content":"使用 React 的 map() 方法来遍历生成 5 个 div 块,并使用随机颜色来设置每个 div 的背景色。\n\n首先,在 React 组件中定义一个数组 colors,包含 5 种不同的颜色值。可以使用 css 的颜色名称或十六进制颜色代码。\n\njsx\nimport React from 'react';\n\nclass App extends React.Component {\n render() {\n const colors = ['red', 'blue', 'green', 'yellow', 'orange'];\n\n return (\n <div>\n {colors.map((color, index) => (\n <div key={index} style={{ backgroundColor: color, width: '100px', height: '100px' }}></div>\n ))}\n </div>\n );\n }\n}\n\nexport default App;\n\n\n在上面的代码中,我们使用 map() 方法遍历 colors 数组,并为每个颜色创建一个 div 块。我们使用 index 作为 key 属性来保持唯一性。每个 div 块的背景色通过 style 属性的 backgroundColor 来设置,宽度和高度也设置为 100px。\n\n这样就生成了 5 个颜色不一样的 div 块。"}

React 遍历生成 5 个不同颜色 div 块 - 完整示例代码

原文地址: https://www.cveoy.top/t/topic/ql69 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录