【问题标题】:Can my empty TextInput value be sent to the DataProvider as empty string instead of converted to null?可以将我的空 TextInput 值作为空字符串发送到 DataProvider 而不是转换为 null 吗?
【发布时间】:2020-07-11 19:18:16
【问题描述】:

我在<SimpleForm> 中使用<TextInput>,当我在运行时清除该值时,react-admin 在将值发送到DataProvider 时将属性的值设置为null。我想存储空字符串而不是 null。那可能吗?如果有,怎么做?

【问题讨论】:

  • 如何在运行时清除这些值?
  • @MiguelAraya 用空字符串替换空值
  • 我期待一些代码,在 FormDataConsumer 中?
  • @MiguelAraya 用户正在清除该值(例如,通过删除文本框中的文本),而不是通过调用代码

标签: react-admin


【解决方案1】:

您可以为此使用 react-final-form parse 道具(请参阅 https://final-form.org/docs/react-final-form/types/FieldProps#parse):

<TextInput
    source="author.name"
    parse={value => value}
/>

默认会将空字符串转换为undefined(参见https://final-form.org/docs/final-form/faq#why-does-final-form-set-my--field-value-to-undefined),react-admin 会将那些未定义的值转换为 null。

【讨论】:

    【解决方案2】:

    react-admin 的当前版本允许您使用 sanitizeEmptyValues 属性更改此行为:

    export const PostEdit = (props) => (
        <Edit {...props}>
            <SimpleForm sanitizeEmptyValues={false}>
                <TextInput source="title" />
                <JsonInput source="body" />
            </SimpleForm>
        </Edit>
    );
    

    更多详情见官方文档:https://marmelab.com/react-admin/CreateEdit.html#setting-empty-values-to-null

    【讨论】:

      【解决方案3】:

      你可以尝试添加initialValue="" prop进去,比如

      <TextInput initialValue="" />
      

      当它是nullundefined时,它将覆盖它为一个空字符串

      【讨论】:

      • 完成不同的事情
      猜你喜欢
      • 2012-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 2020-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多