You need to enable JavaScript to run this app. React中如何定义包含条件判断元素的数组
优惠活动
大模型
产品
解决方案
定价
更多

React中如何定义包含条件判断元素的数组

正确实现代码

const tableFilterFields = [
  // 固定展示的起始日期字段
  {
    label: "from",
    name: "StartDate",
    type: FilterControls.DatePicker,
    defaultValue: new Date(new Date().setDate(new Date().getDate() - 3100)),
  },
  // 条件加载的字段组
  ...(props.id === undefined
    ? [
        {
          label: "IdentityTitle",
          name: "IdentityTitle",
          type: FilterControls.Input,
        },
        {
          label: "AccountCode",
          name: "AccountCode",
          type: FilterControls.Input,
        },
        {
          label: "InstrumentPersianCode",
          name: "InstrumentPersianCode",
          type: FilterControls.Input,
        },
        {
          label: "TradeSideTitle ",
          name: "TradeSideTitle",
          type: FilterControls.Input,
        }
      ]
    : [
        {
          label: "InstrumentPersianCode",
          name: "InstrumentPersianCode",
          type: FilterControls.Input,
        },
        {
          label: "TradeSideTitle",
          name: "TradeSideTitle",
          type: FilterControls.Input,
        }
      ]
  )
];

实现说明

  • 原写法不符合JS语法:三元运算符只能返回单个值,不能直接并列返回多个数组元素
  • 这里搭配**数组扩展运算符...**实现需求:把不同条件下要加载的多个字段放在独立数组中,再通过扩展运算符将对应数组的元素拆分插入到tableFilterFields主数组中,完全匹配你需要的条件加载逻辑
  • 后续需要调整字段时,直接修改对应分支的数组内元素即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 07:54:02