我在样式主题中定义了三种背景颜色。
avatar: {
backgroundColor: red[500],
},
orangeAvatar: {
margin: 10,
color: '#fff',
backgroundColor: deepOrange[500],
},
purpleAvatar: {
margin: 10,
color: '#fff',
backgroundColor: deepPurple[500],
},
每当加载头像时,我想随机选择其中一个。
<Card>
<CardHeader
avatar={
<Avatar id="av" aria-label="Recipe"
className={classes.avatar}>{this.props.userName.charAt(0).toLocaleUpperCase()}
</Avatar>}
title={this.props.userName} disableTypography={true}/>
<CardActionArea disabled={this.state.images.length == 1 ? true : false}>
<CardMedia
id={this.props.ownerId}
className={classes.media}
image={this.state.images[this.state.imageIndex]}
onClick={this.handleOnClick}
/>
</CardActionArea>
</Card>
有什么建议吗?
谢谢
最佳答案
多种方式来做你想做的事。我的建议:将 3 个类放在一个数组中,每次选择一个 0 到 2 之间的随机数,然后分配该类名:
<Avatar className={classes[Math.floor(Math.random() * 3)]}.../>
关于reactjs - 随机设置 <Avatar> 背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55243989/