【问题标题】:<SelectInput>: how to populate choices depending on record data in Edit component of react-admin?<SelectInput>:如何根据 react-admin 的 Edit 组件中的记录数据填充选项?
【发布时间】:2018-07-27 16:23:21
【问题描述】:

我需要根据记录的字段值显示不同的选择。

我需要的代码如下所示:

const myChoicesGenerator = (record) => {
    if (record.field === false) {
      return ['a', 'b'];
    } else {
      return ['b', 'c'];
    }

<SelectInput ... choices = {myChoicesGenerator}/>

但不幸的是,我无法在“选择”属性中传递函数,所以这段代码不起作用。

有办法吗?

【问题讨论】:

    标签: react-admin


    【解决方案1】:

    您可以使用&lt;FormDataConsumer /&gt; 来获取当前记录并将其传递给您的函数。

    <FormDataConsumer>
        {
            ({formData, ...rest}) =>
                <SelectInput 
                     choices={myChoiceGenerator(formData)}
                     {...rest}
                />
        }
    </FormDataConsumer>
    

    文档:https://marmelab.com/react-admin/Inputs.html#linking-two-inputs

    我不知道['a', 'b'] 的值是否对&lt;SelectInput /&gt; 有效。考虑使用documentation 中所述的元组列表(idname)。

    【讨论】:

    • 是的,它有效,不要忘记 上的 source 属性
    • 如果choices 应该来自服务器怎么办? Choices 不是async,那我们该怎么做呢?
    • @user2078023 您可以使用&lt;ReferenceInput /&gt; 从服务器加载您的选择。 (marmelab.com/react-admin/Inputs.html#referenceinput)
    猜你喜欢
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 2011-01-25
    • 2015-07-20
    • 2012-04-30
    • 2019-02-15
    相关资源
    最近更新 更多