【问题标题】:How can I conditionally format the label for a field in react-admin?如何有条件地格式化 react-admin 中字段的标签?
【发布时间】:2019-04-06 16:04:33
【问题描述】:

我的编辑视图中有这个代码部分:

         <FormTab label="Jellemzok">
             <SelectInput label="Tipus" source="type" choices={[
                 {id: 0, name: "type1"},
                 {id: 1, name: "type2"},
                 {id: 2, name: "type3"},
                 {id: 3, name: "type4"},
                 {id: 4, name: "type5"},
                 {id: 5, name: "type6"},
                 {id: 6, name: "type7"},
                 {id: 7, name: "type8"},
             ]} optionText="name" />
             <TextInput source="data_1" />
             <TextInput source="data_2" />
             <TextInput source="data_3" />
             <TextInput source="data_4" />
             <TextInput source="data_5" />
             <TextInput source="data_6" />
         </FormTab>

我必须根据上面选择的类型标记数据字段。

所以:

如果我选择“type1”,我的标签应该是:

             <TextInput label="label1" source="data_1" />
             <TextInput label="label2" source="data_2" />
             <TextInput label="label3" source="data_3" />
             <TextInput label="label4" source="data_4" />
             <TextInput label="label5" source="data_5" />
             <TextInput label="label6" source="data_6" />

但如果我选择“type6”,我的标签应该是这样的:

             <TextInput label="this_is_another_label1" source="data_1" />
             <TextInput label="this_is_another_label2" source="data_2" />
             <TextInput label="this_is_another_label3" source="data_3" />
             <TextInput label="this_is_another_label4" source="data_4" />
             <TextInput label="this_is_another_label5" source="data_5" />
             <TextInput label="this_is_another_label6" source="data_6" />

我怎样才能简单地做到这一点?

【问题讨论】:

  • 有什么建议吗?

标签: javascript reactjs react-native jsx react-admin


【解决方案1】:

您需要使用 FormDataConsumer 组件:

<FormDataConsumer> {({ formData }) => { const label = formData.type === 0 ? "label" : "this_is_another_label" return ( <> <TextInput label={label + 1} source="data_1" /> <TextInput label={label + 2} source="data_2" /> <TextInput label={label + 3} source="data_3" /> <TextInput label={label + 4} source="data_4" /> <TextInput label={label + 5} source="data_5" /> <TextInput label={label + 6} source="data_6" /> </> ) }} </FormDataConsumer>

【讨论】:

  • 谢谢麦克斯!它正在工作。如果我只想在定义 formData.type 的情况下使其可见,我应该将选择器放在哪里?到回报?还是在 const 之前?
  • 在 const 之前更好,只需明确检查未定义: if (formData.type !== undefined) {...}
猜你喜欢
  • 1970-01-01
  • 2021-09-26
  • 2016-07-27
  • 2018-12-02
  • 1970-01-01
  • 2020-02-09
  • 2012-02-01
  • 2012-04-17
  • 2021-12-24
相关资源
最近更新 更多