gpt4 book ai didi

javascript - React - 从 JSON 响应动态设置背景图像

转载 作者:行者123 更新时间:2023-11-28 16:55:08 27 4
gpt4 key购买 nike

我正在从我的 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com