标签: react-hook-form

是的,react-hook-form:如何在表单中创建条件必填字段?

阿门德

我有一个使用 Material UI、react-hook-from 的表单,是的。

该表单具有三组无线电组(例如:radio-g1、radio-g2、radio-g3),并且用户必须从 radio-g1、radio-g2 中至少选择两个选项。此外,如果他们从 radio-g2 中选择“其他”选项,则会显示另一个必填字段 radio-g3。

最后,radio-g3 在隐藏时不是强制性的。

任何帮助将不胜感激。这是一些示例代码:

const schema = yup.object().shape({
  radioG1: yup.string().required("Please select an Avenger"),
  radioG2: yup.string().required("Please select an Avenger"),
  radioG3: yup.string().required("Please select an Avenger")
});

const App = () => {
  const [show, setShow] = useState(false);

  const methods = useForm({
    mode: "all",
    shouldUnregister: true,
    resolver: yupResolver(schema)
  });

  const {
    handleSubmit,
    control,
    formState: { errors }
  } = methods;

  const onSubmit = (data) => {
    alert(JSON.stringify(data));
  };

  return (
    <FormProvider {...methods}>
      <form …
Run Code Online (Sandbox Code Playgroud)

reactjs material-ui yup react-hook-form

6
推荐指数
1
解决办法
9961
查看次数

如何通过在react中使用react-hook-form来获取react-phone-input-2值

我在提交时获取 TextField 值,但不是 ReactPhoneInput 值,如何使用react-hook-form获取该值

import ReactPhoneInput from "react-phone-input-2"
import {TextField,Button}from "@material-ui/core"

const {register, handleSubmit,formState: { errors }} = useForm()

const getData= (data) => {
   console.log(data.username)
   console.log(data.username);
}

Run Code Online (Sandbox Code Playgroud)

形式

<form onSubmit={handleSubmit(getData)} >

  <TextField {...register("username")} />

   <ReactPhoneInput
      inputExtraProps={{
        name: "phone",
        required: true,
        autoFocus: true
      }}

      country={"in"}
       onlyCountries={["in"]}                     
       countryCodeEditable={false}
        specialLabel={"Player Mobile Number"}
       rules={{ required: true }}
     />
<Button type='submit>Submit</Button> 
</form>
Run Code Online (Sandbox Code Playgroud)

reactjs react-hook-form

6
推荐指数
1
解决办法
5829
查看次数

添加 debounce 到反应钩子形式

我使用react-hook-forms 设置了以下受控组件。

          <Controller
            control={control}
            name={"test"}
            render={({ field: { onChange, value, name } }) => (
              <Dropdown
                name={name}
                value={value}
                handleChange={onChange}
                options={foodCategories()}
              />
            )}
          />

Run Code Online (Sandbox Code Playgroud)

我想调用防抖功能,并且尝试执行以下操作:

            handleChange={debounce(onChange, 500)}
Run Code Online (Sandbox Code Playgroud)

但我不断收到错误抛出:

This synthetic event is reused for performance reasons, Objects are not valid as a React child (found: object with keys {dispatchConfig, _targetInst, nativeEvent, type, target, currentTarget, eventPhase, bubbles, cancelable, 
Run Code Online (Sandbox Code Playgroud)

如何在受控反应钩子表单组件上调用去抖?

debouncing reactjs react-hook-form

6
推荐指数
1
解决办法
7540
查看次数

在react-hook-form中的“UseFormReturn”类型上不存在属性“errors”

当我使用react-hook-form时,我无法从react-hook-form解构错误对象。

 const { register, handleSubmit, reset, setValue, getValues, errors, formState } = useForm({
        resolver: yupResolver(validationSchema)
    });
Run Code Online (Sandbox Code Playgroud)

reactjs react-hook-form

6
推荐指数
1
解决办法
7423
查看次数

根据状态变量进行条件 Yup 验证

仅当给定变量的状态为 true 时,是否可以使用 Yup 解析器 RHF 有条件地验证文本字段。

我研究了很多但找不到例子。

谢谢

reactjs yup react-hook-form

6
推荐指数
1
解决办法
1万
查看次数

React-hooks-form 与 Material UI TextField 相关的字段

使用react-hooks-form,我尝试根据另一个字段值更新一个字段。我面临的错误是我的值未在数据对象中注册。

这是我的代码:

const { handleSubmit, control  } = useForm({});
const [dateValue, setDateValue] = useState()

const onSubmit = (data) => {console.log(data.week)} \\ undefined


   <form
          className={classes.root}
          autoComplete="on"
          onSubmit={handleSubmit(onSubmit)}
        >
                <Controller
                  name="date"
                  control={control}
                  defaultValue={props.operation === 'edit' ? props.values.date : null}
                  render={({ field: { onChange, value }, fieldState: { error } }) => (
                    <TextField
                      id="date"
                      type="date"
                      label="date"
                      value={value}
                      className={classes.textField}
                      onChange={(event) => {
                        onChange(event.target.value); 
                        setDateValue(event.target.value);
                      }}
                      error={!!error}
                      helperText={error ? error.message : null}
                      InputLabelProps={{
                        shrink: true,
                      }}
                    />
                  )}
                  rules={{ required: 'Date is required' }} …
Run Code Online (Sandbox Code Playgroud)

reactjs material-ui react-hooks react-hook-form

6
推荐指数
1
解决办法
5542
查看次数

带 React-hook-form 的 Material UI (MUI) 日期选择器

我正在创建一个带有日期字段的表单。我正在使用 MUI 和 react-hook-form 进行验证。我尝试以两种不同的方式呈现该字段,但是在提交表单时我没有得到预期的值:

渲染1

使用控制器组件:

const [originalReleaseDate, setOriginalReleaseDate] = useState(null);

<Controller
                                name={"original_release_date"}
                                defaultValue={originalReleaseDate}
                                control={control}
                                render={({field}) =>
                                    <LocalizationProvider dateAdapter={AdapterDateFns}>
                                        <DatePicker
                                            label="Original Release Date"
                                            value={originalReleaseDate}
                                            onChange={(newValue) => {
                                                setOriginalReleaseDate(newValue);
                                            }}

                                            renderInput={(params) =>
                                                <TextField
                                                    {...params}
                                                />}
                                        />
                                    </LocalizationProvider>
                            }
                            />
Run Code Online (Sandbox Code Playgroud)

当我以这种方式渲染字段时,我会在提交表单后null得到。original_release_date

渲染2

{...register("reissue_release_date")}直接使用而不是react-hook-form 受控组件注册字段。

const [reissueReleaseDate, setReissueReleaseDate] = useState(null);

<LocalizationProvider dateAdapter={AdapterDateFns}>
                                <DatePicker
                                    label="Reissue Release Date"
                                    value={reissueReleaseDate}
                                    onChange={(newValue) => {
                                        setReissueReleaseDate(newValue);
                                    }}

                                    renderInput={(params) =>
                                        <TextField
                                            {...params}
                                            {...register("reissue_release_date")}
                                        />}
                                />
                            </LocalizationProvider>
Run Code Online (Sandbox Code Playgroud)

这种方法已经成功一半了。如果我手动输入日期,那么我将在提交时获取其值,但是如果我使用日期选择器,然后提交我得到的表单""

知道发生了什么事吗?

javascript reactjs material-ui react-hook-form

6
推荐指数
2
解决办法
2万
查看次数

使用 zod 联合模式进行 Typescript React Hook 表单错误处理

我想制作一个动态表单,根据布尔值显示不同的输入字段。

当调用react-hook-form包的useForm时,我使用zod对象来验证我的输入。该对象是另外两个 zod 对象的并集(每个布尔值对应一个对象)。这会导致错误类型仅显示 TypeScript 中的共享选项。

运行代码时一切正常并显示错误。但我仍然不喜欢不再提供类型安全。这个问题有解决办法吗?

import { zodResolver } from "@hookform/resolvers/zod"
import React from "react"
import { useForm } from "react-hook-form"
import { z } from "zod"

const TrueSchema = z.object({
    isTrue: z.literal("true"),
    trueInput: z.string().min(1, "Required, true"),
})

const FalseSchema = z.object({
    isTrue: z.literal("false"),
    falseInput: z.string().min(1, "Required, false"),
})

const FormSchema = z.discriminatedUnion("isTrue", [TrueSchema, FalseSchema])
type FormSchemaType = z.infer<typeof FormSchema>

function Example() {
    const {
        register,
        watch,
        handleSubmit,
        formState: { errors },
    } = useForm<FormSchemaType>({
        resolver: zodResolver(FormSchema),
        defaultValues: …
Run Code Online (Sandbox Code Playgroud)

typescript reactjs react-hook-form zod

6
推荐指数
1
解决办法
4387
查看次数

React hook 表单不观察数组字段中的字段

我的反应挂钩表单中有一个字段数组,其中有一个复选框字段。我想观看该字段,但我只能观看整个数组字段,如下所示:

\n
const Period = ({ item, index, datepicker }) => {\n    const { control } = useFormContext<InntektFormValues>();\n    const value = useWatch({\n        control,\n        name: "incomes",\n    });\n\n\n    return value[index].selected datepicker : <div className="min-w-[160px]"></div>;\n};\n
Run Code Online (Sandbox Code Playgroud)\n

这是我映射字段数组的地方:

\n
export const IncomeTable = () => {\n    const { control } = useFormContext<IncomeFormValues>();\n    const incomeField = useFieldArray({\n        control,\n        name: "incomes",\n    });\n\n   \n    return ({incomes.fields.map((item, index) => (\n                    <TableRowWrapper\n                        key={item.id}\n                        cells={[\n                            <Period\n                                item={item}\n                                index={index}\n                                datepicker={\n                                    <FormControlledDatePicker\n                                        key={`incomes[${index}].from`}\n                                        name={`incomes[${index}].from`}\n                                        label="From"\n                                        placeholder="DD.MM.\xc3\x85\xc3\x85\xc3\x85\xc3\x85"\n                                        defaultValue={item?.from ?? null}\n                                        hideLabel\n                                    />\n                                }\n …
Run Code Online (Sandbox Code Playgroud)

reactjs react-hook-form

6
推荐指数
1
解决办法
3036
查看次数

反应钩子形式,Zod。以支持添加和编辑的形式处理图像上传的推荐方法是什么?

以支持添加和编辑产品的形式处理图像上传的推荐方法是什么?这是我当前的实现,有两个选项,有什么改进建议吗?

这是当图像转换为 File 对象并将其设置为表单中图像的默认值时的第一个选项:

const getFileFromUrl = async (url: string) => {
  const res = await fetch(url);
  const blob = await res.blob();
  return new File([blob], 'image', { type: blob.type });
};

const productForm1Schema = z.object({
  name: z.string().min(1, { message: 'Name is required' }),
  image: z
    .custom<File>((v) => v instanceof File, {
      message: 'Image is required',
    })
});

export type ProductForm1Values = z.infer<typeof productForm1Schema>;

interface ProductForm1Props {
  product?: Product;
}

export const ProductForm1 = ({ product }: ProductForm1Props) => {
  const …
Run Code Online (Sandbox Code Playgroud)

file-upload reactjs react-hook-form zod

6
推荐指数
0
解决办法
4383
查看次数