You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React列表项中Div背景颜色不显示问题排查

问题分析与修复方案

核心问题:背景色属性语法错误

你代码里背景色不生效的直接原因是map生成Div时,backgroundColor的值错误地用了额外的花括号包裹:

// 错误写法
<div style={{height:100, width:100, backgroundColor:{color} }}></div>

color本身就是randomRGb()返回的合法RGB字符串(比如rgb(123,45,67)),React的style对象中,属性值直接传入该字符串即可,不需要再用{}包裹。正确写法应为:

// 正确写法
<div style={{height:100, width:100, backgroundColor: color }}></div>

额外可优化点

  1. 无效的Button导入:你写了import { Button, } from 'react';,但React本身并没有导出Button组件,代码里实际用的是原生<button>标签,所以这行导入可以直接删除,避免混淆。
  2. 关于key的使用:虽然用数组索引i作为key能运行,但在元素顺序可能变化的场景下,官方更推荐使用唯一标识作为key。不过这个不影响当前功能生效,属于优化项。

修改后的完整代码

import React, { useState } from 'react'

const ColorScreen = (props) => {
    const [colors, setColors] = useState([])
    console.log(colors);

    const colorDivs = colors.map((color,i) => 
        <li key={i}>
            <div style={{height:100, width:100, backgroundColor: color }}></div>
        </li>
    )
 
    return (
        <div>
            <div style={{height:100, width:100, backgroundColor: randomRGb() }}></div>
            <button onClick={() => 
                setColors([...colors, randomRGb()])
            }> Add a Color</button> 
            <ul>{colorDivs}</ul>
        </div>  
    )
}

const randomRGb = ()  => {
    const red = Math.floor(Math.random()*256);
    const green = Math.floor(Math.random()*256);
    const blue = Math.floor(Math.random()*256);

    return `rgb(${red},${green},${blue})`
}

export default ColorScreen;

内容的提问来源于stack exchange,提问作者Patrick Bentley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 04:45:33