每个 colored颜色 分量(红色、绿色、蓝色)的随机值为0-255.您需要限制为0 - 127才能确保生成的 colored颜色 更暗.
padStart(2, '0')
确保每个组件有两位十六进制形式的数字
utils.js
export function randomColors(persons) {
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;
}
在你的react 组件内部.
const colors = useMemo(() => {
return randomColors(persons)
}, [persons]);
CODESANDBOX