React中的随机背景图像

3

我正在开发一个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]; - Oleksandr Paiziak
谢谢,现在可以了! - Julien Berthoud
你能检查一下我的答案是否正确吗? - Oleksandr Paiziak
1个回答

4

您现在将其作为对象,能否将其更改为const pictureArray = [skyPicture1, skyPicture2, skyPicture3, skyPicture4];


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接