如何为数组中的每个项目分配随机颜色?

Sha*_*G97 0 javascript css colors reactjs

我编写了 JavaScript 代码来从颜色列表中获取随机颜色:

const colours = [blue[800], green[500], orange[500], purple[800], red[800]];
const colour = colours[Math.floor(Math.random() * colours.length)];
Run Code Online (Sandbox Code Playgroud)

在我的 JSX 代码中,我用随机颜色渲染图像

{this.state.data.map((n, i) => {
    return (
    <Avatar style={{backgroundColor: colour}}>{n.author.charAt(0).toUpperCase()}</Avatar>
    );
})}
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是渲染的每个对象都将具有相同的随机颜色,例如橙色。我想要实现的是每个渲染的项目都有不同的颜色,但我不确定如何实现这一点。

小智 5

const colours = [blue[800], green[500], orange[500], purple[800], red[800]];
const getColour = () => colours[Math.floor(Math.random() * colours.length)];

{this.state.data.map((n, i) => {
   return (
    <Avatar style={{backgroundColor: getColour()}}> 
      {n.author.charAt(0).toUpperCase()}
    </Avatar>
   );
})}
Run Code Online (Sandbox Code Playgroud)