mui 自动完成与react-hook-form:formData中的defaultValue

Mac*_*Fly 3 reactjs material-ui next.js react-hook-form

我将 Autocopmlete 组件的 defaultValue 设置如下:

<Controller
  control={control}
  name={name}
  render={({field: {onChange, value}}) => (
    <Autocomplete
      freeSolo={freeSolo}
      options={options}
      renderInput={params => {
        return <TextField {...params} label={label} margin="normal" variant="outlined" onChange={onChange} />
      }}
      onChange={(event, values, reason) => onChange(values)}
      defaultValue={defaultValue}
    />
  )}
/>
Run Code Online (Sandbox Code Playgroud)

该值基于defaultValue很好地显示。但是,当我单击提交按钮时,如果我不使用自动完成组件,则自动完成字段的值始终未定义。这是我注册钩子和组件的方法(简化代码)

const customerSchema = yup.object().shape({
  route: yup.string().nullable()
})
  
const {control, handleSubmit} = useForm({
    resolver: yupResolver(customerSchema)
  })

  const onSubmit = formData => {
    console.log(formData) // autocomplete is undefined if no action on the autocomplete 
  }

<form noValidate autoComplete="off" onSubmit={handleSubmit(onSubmit)}>
 <AutoCompleteInput
        control={control}
        name="route"
        label="route"
        options={customers_routes.map(option => option.route_name)}
        defaultValue={customer.route}
        freeSolo={false}
      />
  <Button type="submit">
        Update
      </Button>
  </form>
Run Code Online (Sandbox Code Playgroud)

当我单击“提交”时,如何使表单数据中的路线字段始终可用?

Sae*_*loo 6

为什么不使用defaultValues以下选项useForm

const {control, handleSubmit} = useForm({
  resolver: yupResolver(customerSchema),
  defaultValues: { route: customer.route },
});
Run Code Online (Sandbox Code Playgroud)

您可以使用defaultValueprop ,而不是发送prop,如下所示:AutoCompletevalue

<Controller
  control={control}
  name={name}
  render={({ field: { onChange, value } }) => (
      <Autocomplete
        freeSolo={freeSolo}
        options={options}
        renderInput={(params) => {
          return (
            <TextField
              {...params}
              label={label}
              margin="normal"
              variant="outlined"
              onChange={onChange}
            />
          );
        }}
        onChange={(event, values, reason) => onChange(values)}
        value={value}
      />
  )}
/>
Run Code Online (Sandbox Code Playgroud)