我正在从我的Wordpress API中获取数据以显示在我的React应用中。我正在尝试将发布的特色图片显示为元素上的背景图片,但似乎无法使其正常工作。
这是JSON响应的示例:
{
"id": 1,
"title": {
"rendered": "My First Post"
},
"featured_image": "http://example.com/wp-content/uploads/2019/08/featured.jpg"
}
这是我尝试based on this question设置背景图像的方法:
<div className="featured-image" style={{backgroundImage: 'url(${this.props.post.featured_image})'}}></div>
当我检查元素时,似乎没有解析JSON,因为它是这样的:
<div class="featured-image" style="background-image: url("${this.props.post.featured_image}");"></div>
答案 0 :(得分:3)
您使用的是字符串,而不是template string。
尝试一下:
<div
className="featured-image"
style={{
backgroundImage: `url(${this.props.post.featured_image})`
}}>
</div>