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

