我正在从我的 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>
最佳答案
您使用的是字符串,而不是 template string 。
试试这个:
<div
className="featured-image"
style={{
backgroundImage: `url(${this.props.post.featured_image})`
}}>
</div>
关于javascript - React - 从 JSON 响应动态设置背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59349749/