簡體   English   中英

如何在 react-hook-forms 中重置自動完成?

[英]How to reset Autocomplete in react-hook-forms?

我正在使用react-hook-forms並嘗試在提交后重置所有表單字段。 問題是,在我的例子中,自動完成接受對象作為值。

我嘗試將defaultValue設置為{} ,但收到以下消息:

Material-UI:自動完成的getOptionLabel方法返回未定義而不是 {} 的字符串

是否有任何變體可以重置自動完成功能?

這是CodeSandbox的鏈接

聚會有點晚了,但如果其他人需要的話,這里有一個解決方案。

假設您的自動完成包含在 Controller 中,您所要做的就是明確檢查自動完成中的值。 參考以下了解更多

<Controller
name="category"
control={control}
rules={{ required: true }}
render={({ field }) => (
    <Autocomplete
        fullWidth
        options={categories}
        {...field}
        // =====================================================
        // Define value in here
        value={
            typeof field.value === "string"
                ? categories.find((cat) => cat === field.value)
                : field.value || null
        }
        // =====================================================
        onChange={(event, value) => {
            field.onChange(value);
        }}
        renderInput={(params) => (
            <TextField
                {...params}
                label={t("product_category")}
                error={Boolean(errors.productCategory)}
                helperText={errors.productCategory && "Product Category is required!"}
            />
        )}
    />
)}
/>

這應該可以解決問題!

要使用 react hook 表單的reset來重置AutoComplete的值,您應該將value屬性添加到 AutoComplete,其他方式重置不會 function,請參見示例:


import { useEffect, useState } from 'react'
import {
  Autocomplete,
  TextField,
  reset,
} from '@mui/material'
...

const {
  ...
  setValue,
  control,
  formState: { errors },
} = useForm()

useEffect(() => {
  reset({
    ...
    country: dataEdit?.country ? JSON.parse(dataEdit?.country) : null,
  })
  // eslint-disable-next-line react-hooks/exhaustive-deps
}, [dataEdit])


...
<Controller
  control={control}
  name="country"
  rules={{
    required: 'Veuillez choisir une réponse',
  }}
  render={({ field: { onChange, value } }) => (
    <Autocomplete
      value={value || null}
      options={countries}
      getOptionLabel={(option) => option.name}
      onChange={(event, values) => {
        onChange(values)
        setSelectedCountry(values)
        setValue('region', null)
      }}
      renderInput={(params) => (
        <TextField
          {...params}
          label="Pays"
          placeholder="Pays"
          helperText={errors.country?.message}
          error={!!errors.country}
        />
      )}
    />
  )}
/>

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM