如何防止在ReactJS中重新呈现随机颜色

问题描述 投票:0回答:2

我在渲染时为三个图像图标分配了随机颜色。但是,当我单击按钮来渲染对话框弹出窗口时,图标的颜色将再次重新渲染。如何防止这种情况发生?

const colours = [blue[800], green[800], lime[500], brown[500], 
grey[500], yellow[800], blueGrey[500],
orange[800], purple[800], red[800], pink[800], indigo[800], cyan[500], teal[500],];
const colour = () =>  colours[Math.floor(Math.random() * colours.length)];
handleClick= () => {
    this.setState({
        openDialog: true
    }); 
}
render() {
    return (
    <div>
        <Button onClick={() => this.handleClick()}  variant="contained" >
        Post
        </Button> 

        <Avatar  style={{backgroundColor: colour()}}>S</Avatar>
        <Avatar  style={{backgroundColor: colour()}}>S</Avatar>
        <Avatar  style={{backgroundColor: colour()}}>S</Avatar>

        <Dialog
        keepMounted
        fullWidth = "true"
        onClose={this.handleClose}
        aria-labelledby="customized-dialog-title"
        open={this.state.openDialog}
        >
        </Dialog>
    </div>
    );
}

Codesandbox链接https://codesandbox.io/s/quirky-bouman-8p2zb

javascript css reactjs colors
2个回答
1
投票

正在重新渲染,因为您正在使用openDialog状态更改组件的状态。也许您也可以将计算出的颜色存储在状态中,但是组件本身将重新呈现。最后,它应该显示相同的已经计算出的颜色。

也许在constructor中生成颜色然后将其存储在state中:

constructor() {
  super();
  this.state = {
    openDialog: false,
    colors: [
      colour(),
      colour(),
      colour()
    ]
  };
}

然后以某种方式使用此:

<Avatar  style={{backgroundColor: this.state.colors[0]}}>S</Avatar>
<Avatar  style={{backgroundColor: this.state.colors[1]}}>S</Avatar>
<Avatar  style={{backgroundColor: this.state.colors[2]}}>S</Avatar>

此外,您还需要更改handleClick

handleOpenDialog = () => {
  this.setState(prevState => ({
    ...prevState,
    openDialog: true
  }));
};

我希望有帮助!


0
投票

如果您不想在每次重新渲染中都更新这些颜色,只需将color()函数移出渲染函数即可。

您可以在构造函数中将颜色声明为state,并将其用作按钮的背景色的值。

并根据需要更新状态。

演示:https://codesandbox.io/s/quizzical-margulis-uc610?fontsize=14&hidenavigation=1&theme=dark

© www.soinside.com 2019 - 2024. All rights reserved.