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

React中如何使用嵌套三元运算符按条件渲染指定字符串

修改后代码

const ChildComponent = (data) => {
    const name = data.name //array
    const type = data.type //object

    return (
        <div>
          {/* 嵌套三元运算符实现需求逻辑 */}
          {type?.name ? type.name : type?.id ? type.id : "none"}
        </div>
    );
}

逻辑说明

  • 嵌套三元运算符的判断优先级从左到右执行:
    • 第一层用可选链?.判断type存在且type.name为有效值(非undefined/null/空字符串/0等假值)时,展示type.name
    • 第一层判断不通过时,进入第二层判断:type存在且type.id为有效值时,展示type.id
    • 前两层均不满足时,兜底展示字符串none

不支持可选链语法的兼容写法

如果你的项目环境不支持ES2020的可选链特性,可以改用如下写法避免type为undefined/null时报错:

const ChildComponent = (data) => {
    const name = data.name //array
    const type = data.type //object

    return (
        <div>
          {type && type.name ? type.name : type && type.id ? type.id : "none"}
        </div>
    );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 09:48:00