带有 React 的随机背景图片
Random background image with React
我实际上正在开发 React 应用程序,目前正在尝试显示随机背景图片。
我的想法是导入 4 张图片,将它们放入一个数组中,然后 select 随机选择数组中的一项:
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;
但是根本没有显示图片。有谁知道我做错了什么?
我不知道。
你把它做成object,可以改成const pictureArray = [skyPicture1, skyPicture2, skyPicture3, skyPicture4];
我实际上正在开发 React 应用程序,目前正在尝试显示随机背景图片。 我的想法是导入 4 张图片,将它们放入一个数组中,然后 select 随机选择数组中的一项:
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;
但是根本没有显示图片。有谁知道我做错了什么? 我不知道。
你把它做成object,可以改成const pictureArray = [skyPicture1, skyPicture2, skyPicture3, skyPicture4];