简体   繁体   中英

Curly braces with ` on React

I've a small problem with rendering.

const Image = React.createClass({
getInitialState(){
    return{
        imgUrl: 'cat.jpg'
    }
},

handleChange(e){
        e.target.classList.toggle('active')
},

render(){
    return (

        <div className="handler"

           style={{backgroundImage: 'url(' + this.state.imgUrl + ')'}}
           onClick={this.handleChange}>

        </div>
    )
}
})

ReactDOM.render(
    <Image />,
    document.getElementById('home')
)

Right now I'm adding style for my div this way:

style={{backgroundImage: 'url(' + this.state.imgUrl + ')'}}

When I'm trying to write this way:

`url({this.state.imgUrl})`

it just adds %7D and %7B symbols of { }

What's the correct way to write it and how I can to avoid " + "

Hope someone will help with this easy question :)

It should be `url(${this.state.imgUrl})` .

For your information, It is called Template literals . See this MDN doc to get more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM