You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何将状态变量传入map渲染对象的img src属性?

解决方法

问题出在你访问对象属性的方式上:item.urls.imageSize 是在尝试访问 urls 对象里**名为"imageSize"**的属性,而不是使用状态变量imageSize的值作为属性名。

要实现根据状态变量动态获取对应尺寸的图片地址,需要用方括号属性访问语法,把变量放在方括号里:

{searchImages.map(item => (
    <img className='image-item' key={item.id} src={item.urls[imageSize]} alt='cool'/>
))}

补充说明

假设你的item.urls结构类似这样:

{
  regular: "https://example.com/regular.jpg",
  small: "https://example.com/small.jpg",
  large: "https://example.com/large.jpg"
}

当imageSize状态为"regular"时,item.urls[imageSize]就等价于item.urls.regular,就能正确拿到对应尺寸的图片地址了。

内容的提问来源于stack exchange,提问作者milo2810

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 06:02:41