简体   繁体   English

如何使用 react-hook-form 为 KeyboardDatePicker 设置条件默认值?

[英]How to set a conditional default value for a KeyboardDatePicker with react-hook-form?

I have a form that contains a KeyboardDatePicker from material UI and I want it to have an empty string value ( "" ) as default value when no value is passed to the useForm hook for this field.我有一个包含来自material UIKeyboardDatePicker的表单,我希望它有一个空字符串值( "" )作为默认值,当没有值传递给该字段的useForm挂钩时。

Here's my implementation so far:到目前为止,这是我的实现:

The date picker input field:日期选择器输入字段:

                <MuiPickersUtilsProvider utils={DateFnsUtils}>
                    <Controller
                        name="date"
                        control={control}
                        rules={{ required: true }}
                        defaultValue={getValues().date || ""}
                        as={
                            <KeyboardDatePicker
                                autoOk
                                inputVariant="outlined"
                                format="yyyy-MM-dd"
                                margin="normal"
                                id="date-picker-inline"
                                label="Date"
                                placeholder="yyyy-mm-dd"
                                required
                                error={!!errors.date}
                                helperText={errors.date && "Incorrect entry."}
                                onChange={() => {}}
                                value={() => {}}
                                KeyboardButtonProps={{
                                    "aria-label": "change date",
                                }}
                            />
                        }
                    />
                </MuiPickersUtilsProvider>

And here's my hook for the form:这是我的表格钩子:

const { handleSubmit, getValues, control, register, errors, setValue } = useForm<Project>({
    submitFocusError: false,
    mode: "onBlur",
    defaultValues: project,
});

I am setting the default values of my form with a project but project can be null or undefined and the date property of project can also be null .我正在使用project设置表单的默认值,但project可以是null or undefinedprojectdate属性也可以是null If that's the case I want the default value to be an empty string.如果是这种情况,我希望默认值为空字符串。

Sadly, with this implementation, when I select a date from an empty field to a Date I get a warning telling me that I should not be changing an uncontrolled input of type text to controlled one and the label of the input stack above the value:可悲的是,通过这个实现,当我 select 一个从空字段到日期的Date时,我收到一条警告,告诉我我不应该将文本类型的不受控制的输入更改为受控的输入,并且输入堆栈的label高于该值:

在此处输入图像描述

Is it even possible to have an empty string as the default value for a DatePicker without breaking everything?是否可以在不破坏所有内容的情况下将空字符串作为DatePicker的默认值? If it's possible how should it be implemented?如果可能,应该如何实施?

A moment ago I had a similar situation and solved it by initially setting defaultValue AND initialFocusedDate to null on my Controller .刚才我遇到了类似的情况,并通过在我的null上最初将defaultValueinitialFocusedDate设置为Controller来解决它。

  const [helperText, isError] = useHelperText(name, errors);
  const defaultValue = useDefaultValue(getValues, name, watch);

  return (
    <Controller
      name={name}
      rules={isRequired}
      control={control}

      // here the magic happens
      initialFocusedDate={null} 
      defaultValue={null} 

      as={
        <KeyboardDatePicker
          disableFuture
          {...rest}
          name={name}
          error={isError}
          helperText={helperText}
          required={Boolean(isRequired?.required)}
          disableToolbar
          variant="inline"
          inputVariant={rest.variant}
          format="dd.MM.yyyy"
          id={name}
          label={label}
          invalidDateMessage=""
          KeyboardButtonProps={{
            "aria-label": "change date",
          }}
        />
      }
    />
  );

This way, if no defaultValues are present from useForm , the component displays an empty MUI-input.这样,如果useForm中不存在defaultValues ,则该组件将显示一个空的 MUI 输入。

In order to make an empty value for datepicker you need to pass null as a default value.为了为 datepicker 创建一个空值,您需要将null作为默认值传递。 This codesandbox confirms this behavior https://codesandbox.io/s/relaxed-poitras-5eohr?file=/src/App.jsx此代码框确认此行为https://codesandbox.io/s/relaxed-poitras-5eohr?file=/src/App.jsx

Your problem is with incorrect usage of this 2 values您的问题是这 2 个值的使用不正确

  onChange={() => {}}
  value={() => {}}

These values should accept exactly value of the form input and the callback to change this value without event.这些值应该完全接受表单输入的value和回调以在没有事件的情况下更改此值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM