获取随机颜色函数
以下代码在react项目中运行
import React, { useState, useEffect } from 'react';
import { Button } from 'antd';
const Daily = () => {
const [randomColorSapn, setRandomColorSapn] = useState('');
useEffect(() => {}, []);
const randomColor = () => {
// Generate three random numbers as the three components of an RGB color value
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
// Convert RGB color values to hexadecimal format
const hexR = r.toString(16).padStart(2, '0');
const hexG = g.toString(16).padStart(2, '0');
const hexB = b.toString(16).padStart(2, '0');
// Concatenated into a complete color value string
const hexColor = `#${hexR}${hexG}${hexB}`;
setRandomColorSapn(hexColor);
// return hexColor;
};
return (
<div>
<Button onClick={randomColor}>
<span style={{ color: randomColorSapn }}>获取随机颜色</span>{' '}
</Button>
</div>
);
};
export default Daily;
效果图