CSS ReactJS 动态更改背景图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27966468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 02:54:59  来源:igfitidea点击:

ReactJS change background image dynamically?

cssreactjsreact-jsx

提问by rabishah

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

我试图为以下 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>
  )
}

Thanks for the help

谢谢您的帮助

回答by daniula

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

您尚未指定何时更改backgroundImage,因此我创建了更改它的版本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>
        )
    }
});

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

请注意,backgroundImage: 'url(' + imgUrl + ')'不再必须有尾随分号,实际上尾随分号会导致 React 引发和错误。

回答by Brigand

This is caused by the trailing semicolon in your style. See react issues #2862.

这是由您的样式中的尾随分号引起的。请参阅反应问题 #2862