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

不解构properties参数时,如何简化React图片默认值赋值代码

解决方案

你可以用以下两种方式简化代码,且不需要解构properties参数:

1. 逻辑或运算符(||)

适合当user_image为undefined或空字符串等"假值"时都使用默认图标的场景:

src={properties.user_image || "favicon.ico"}

原理:如果properties.user_image是假值(undefined、""、null、0等),就会取右侧的默认值。

2. 空值合并运算符(??)

更严谨的写法,仅当user_image为undefined或null时才使用默认值,空字符串等其他假值会保留原内容:

src={properties.user_image ?? "favicon.ico"}

原理:空值合并运算符只会在左侧是null或undefined时返回右侧值,避免误替换空字符串这类合法的图片路径。


修改后的组件核心片段:

<Image
  className="image-user-card"
  src={properties.user_image ?? "favicon.ico"} // 替换为你选择的简化写法
  roundedCircle
  alt="user card"
/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 16:42:10