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

React随机颜色组件:RGB值变化但背景色未更新问题

修复RGB模式下背景色不更新的问题

问题根源

  • RGB颜色格式不完整:生成RGB颜色时仅存储了(r,g,b)部分,缺少CSS要求的rgb前缀,导致浏览器无法识别该背景色值。
  • 样式属性语法错误:background: {color}的写法错误,此处无需额外大括号,直接使用变量color即可,否则会被解析为对象而非字符串颜色值。

修改后的完整代码

import { useState, useEffect } from 'react';

export default function RandomColor() {
    const [typeOfColor, setTypeOfColor] = useState('rgb')
    const [color, setColor] = useState('rgb(0,0,0)')

    function randomColorUtility(length) {
        return Math.floor(Math.random() * length);
    }

    function handleCreateRandomHexColor() {
        const hex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"];
        let hexColor = "#";

        for (let i = 0; i < 6; i++) {
            hexColor += hex[randomColorUtility(hex.length)]
        }
        
        setColor(hexColor);
    }

    function handleCreateRandomRGBColor() {
        let r = randomColorUtility(256);
        let g = randomColorUtility(256);
        let b = randomColorUtility(256);
        // 补充rgb前缀,生成完整的CSS RGB格式
        setColor(`rgb(${r},${g}, ${b})`);
    }

    useEffect(() => {
        if (typeOfColor === "rgb") handleCreateRandomRGBColor();
        else handleCreateRandomHexColor();
    }, [typeOfColor]);

    return (
        <div 
            onClick={
                typeOfColor === "hex"
                ? handleCreateRandomHexColor
                : handleCreateRandomRGBColor
            }
            style={{
                width: "100vw", // 修正无效宽度单位为100vw
                height: "100vh",
                background: color, // 移除多余大括号
            }}
        >
            <button onClick={() => setTypeOfColor("hex")}>Create HEX Color</button>
            <button onClick={() => setTypeOfColor("rgb")}>Create RGB Color</button>
            <div 
                style={{
                    display: "flex",
                    justifyContent: "center",
                    alignItems: "center",
                    color: "#fff",
                    fontSize: "60px",
                    marginTop: "50px",
                    flexDirection: 'column',
                    gap: '20px'
                }}
            >
                <h3>{typeOfColor === "rgb" ? "RGB Color" : "Hex Color"} </h3>
                <h1> {typeOfColor === "rgb" ? color.slice(4) : color} </h1>
                {/* RGB模式下去掉前缀,保持原需求的展示格式 */}
            </div>
        </div>
    );
}

额外优化点

  • 修正了无效宽度单位100w为标准的100vw,确保容器占满视口宽度。
  • 简化了点击事件的写法,直接传递函数引用替代箭头函数包裹。
  • 颜色值展示时,RGB模式自动去除rgb前缀,和原需求的展示效果保持一致。

内容的提问来源于stack exchange,提问作者Shivam Chaturvedi 58

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 03:03:09