ReactJS动态更改背景图像? [英] ReactJS change background image dynamically?

查看:712
本文介绍了ReactJS动态更改背景图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为以下div动态更改背景图像样式:

I was trying to change background image style dynamically for the following div:

这是我的更改它的组件,

Here is my component for changing it,

render: function() {
  var divImage = {
    backgroundImage : "url(" + this.state.song.imgSrc + "),url(" + this.state.nextImgSrc + ");" 
  };

  return (
    <li>
      <div ref="image-pane" className="player" style={divImage}></div>
    </li>
  )
}

感谢帮助

推荐答案

您尚未指定何时更改 backgroundImage ,因此我创建了使用 onClick 进行更改的版本:

You haven't specified when would you like to change backgroundImage, so I've created version which changes it with onClick:

React.createClass({
    getInitialState: function () {
        nextImg: false,
    },
    handleClick: function () {
        this.setState({ nextImg: !this.state.nextImg })
    },
    render: function() {
        var imgUrl = this.state.nextImg ? this.state.nextImgSrc : this.state.song.imgSrc;
        var divStyle = {
            backgroundImage: 'url(' + imgUrl + ')'
        }

        return (
            <li>
                <div ref="image-pane" style={divStyle} onClick={this.handleClick} className="player"></div>
            </li>
        )
    }
});

注意 backgroundImage:'url('+ imgUrl +')'不再必须具有尾部分号,实际上尾部分号将导致React引发并出错。

Notice that backgroundImage: 'url(' + imgUrl + ')' no longer must have trailing semicolon, in fact the trailing semicolon will cause React to raise and error.

这篇关于ReactJS动态更改背景图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆