ReactJS change background image dynamically?

僤鯓⒐⒋嵵緔 提交于 2019-12-03 23:16:12
daniula

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>
        )
    }
});

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!