css - 使用 React 的随机背景图像
问题描述
我实际上正在开发一个 React 应用程序,目前正在尝试显示随机背景图像。我的想法是导入 4 张图片,将它们放在一个数组中并随机选择数组中的一项:
import skyPicture1 from '../assets/pictures/sky.jpg'
import skyPicture2 from '../assets/pictures/sky2.jpg'
import skyPicture3 from '../assets/pictures/sky3.jpg'
import skyPicture4 from '../assets/pictures/sky4.png'
class HomeForUnlogged extends Component {
constructor(props) {
super(props)
this.state = {
bgStyle : {
height: "100%",
backgroundPosition: "center",
backgroundRepeat: "no-repeat",
backgroundSize: "cover",
}
}
}
componentWillMount() {
const pictureArray = [{skyPicture1}, {skyPicture2}, {skyPicture3}, {skyPicture4}];
const randomIndex = Math.floor(Math.random() * pictureArray.length);
const selectedPicture = pictureArray[randomIndex];
this.setState({
bgStyle: {
backgroundImage: `url(${selectedPicture})`,
height: "100%",
backgroundPosition: "center",
backgroundRepeat: "no-repeat",
backgroundSize: "cover",
}
})
}
render() {
return (
< div style={this.state.bgStyle} className="bg">
<div className="row" >
<div className="col-sm-4" style={{ marginTop: "30px", padding: "30px" }} > <TextHome /></div>
<div className="col-sm-4" style={{ marginTop: "90px", padding: "30px" }}> <Login history={this.props.history} /></div>
<div className="col-sm-4"> </div>
</div>
</div>
);
}
}
export default HomeForUnlogged;
但是根本没有图片显示。有谁知道,我做错了什么?我没有任何线索。
解决方案
你把它作为对象,你能把它改成 const pictureArray = [skyPicture1, skyPicture2, skyPicture3, skyPicture4];
推荐阅读
- javascript - 使用 Javascript 显示输入(来自 HTML)的特定输出
- python - 什么是与Matlab中的spapi相同的Python插值函数
- laravel - laravel - 将选定的字段发送到函数
- c# - 变量数据类型错误,因为我将小数添加到矢量 3 力的一个轴
- python - 使用 PyMongo 获取按 date_posted 降序排序的不同值
- python - 使用 seaborn distplot 设置轴最大值
- ios - 如何避免此处的搜索栏和 tableview 之间的额外间隙并在两者之间放置分隔符?
- android - 使用 Gradle 构建时的 Firebase-demo/Analytics NoClassDefFoundError 异常
- python - selenium - 单击按钮导出时遇到问题
- php - 从结帐到我的帐户并返回 Woocommerce 的自定义重定向