我有一个
<Avatar/>
组件,里面的文本是颜色 white
,
如何确保其背景颜色为深色,以便可以看到动态生成的文本?
Codesandbox -----> 点击这里
代码:
const colors = useMemo(() => {
const randomColors = persons.map(() => `#${Math.floor(Math.random() * 16777215).toString(16)}`);
return randomColors;
}, [persons]);
每个颜色分量(红、绿、蓝)的随机值是从 0 到 255。您需要限制为 0 - 127 以确保生成的颜色更暗。
padStart(2, '0')
确保每个组件都有两位十六进制形式的数字
const colors = useMemo(() => {
const darkColors = persons.map(() => {
// Generate each color component in the lower half (0-127) of the 0-255 range
const r = Math.floor(Math.random() * 128).toString(16).padStart(2, '0');
const g = Math.floor(Math.random() * 128).toString(16).padStart(2, '0');
const b = Math.floor(Math.random() * 128).toString(16).padStart(2, '0');
return `#${r}${g}${b}`;
});
return darkColors;
}, [persons]);