不解构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
相关产品推荐
相关产品推荐

