标签: react-hook-form

使用register时转换onChange

是否可以使用registerreact-hook-form的just和v7来转换传出值?

我通过覆盖e我传递给的值来做到这一点onChange,但它永远不会成为我设置的值。325

  const { onChange, ...registration } = props.form.register('foo');

  const handleChange = e => {
    const value = e.target.value;
    const transformedValue = 325;
    onChange({
      type: e.type,
      target: {
        name: e.target.name,
        type: e.target.type,
        value: transformedValue
      }
    });
  };

return <input {...registration} onChange={handleChange} />
Run Code Online (Sandbox Code Playgroud)

react-hook-form

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

使用带有自定义 TextInput 的 React hook 表单

我正在尝试将 React hook 形式与自定义 TextInput 结合使用。在我使用材料输入之前,一切都工作正常。我找到了一种可以实现这一目标的方法,但我对此并不满意。

我正在使用useForm钩子

  const {
    register,
    handleSubmit,
    formState: { errors, isValid },
  } = useForm<FormValues>({ resolver: yupResolver(schema), mode: "all" });
Run Code Online (Sandbox Code Playgroud)

我的自定义 TextField (非常简单,因为现在我只想将其注册到表单中):

export interface TextFieldProps {
    id: string;
    error: string | undefined;
    label: string;
    register: UseFormRegister<any>
}

const TextField = ({ id, error, label, register }: TextFieldProps): JSX.Element => {
    return <>
    <input {...register(`${id}`)}></input>
    {error}
    </>
  };
Run Code Online (Sandbox Code Playgroud)

使用该组件:

          <TextField
            register={register}
            id="username"
            label="Username"
            error={errors.username?.message}
          />
Run Code Online (Sandbox Code Playgroud)

这段代码可以工作,但我失去了IMO非常好的功能 - 检查我传递给注册函数的名称。例如,我声明了一些模式:

  const schema = yup.object({
    username: yup.string().required("Username …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-hooks react-hook-form

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

使用react-hook-form上传并保存文件列表

我正在构建一个主要针对使用的浏览器的网站Ionic React。我正在尝试使用 areact-hook-form上传文件列表(以及其他数据)并将它们与其他数据一起保存在 FieldArray 中。

我已经按照Ionic Forum 中的这个答案,使用 IonButton 和输入实现了文件上传。

 <input
       type="file"
       id="file-upload"
       style={{ display: "none" }}
       onChange={() => { setFile(index);}}/>
  <IonButton
       onClick={() => {openFileDialog();}}
       disabled={files === undefined || files[index] === undefined}>
     <IonLabel>Upload file</IonLabel>
     <IonIcon slot="start" />
   </IonButton>
Run Code Online (Sandbox Code Playgroud)

代码:

function openFileDialog() {
    (document as any).getElementById("file-upload").click();
  }

const setFile = (index: number) => (_event: any) => {
    console.log(`Getting file for index ${index}`);

    let f = _event.target.files![0];

    var reader = new FileReader();

    reader.onload = function () { …
Run Code Online (Sandbox Code Playgroud)

reactjs ionic-framework react-hook-form

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

如何在react-hook-form中动态设置defaultValue

我有一个要编辑的页面Productprops值取自 API,并且来自父组件。如何将此值设置为我的Datepicker输入?因为defaultValuefromreact-hook-form是在自定义挂钩中的第一次渲染时缓存的,所以我得到了null.

const ProductEdit = (props) => {
  const { product } = props;
  const { control, register, handleSubmit, formState: { errors } } = useForm();

  ........

  <Controller
     control={control}
     name='dateLaunch'
     defaultValue={() => {
        console.log(product); // return null
     }}
     render={({ field }) => (
        <DatePicker
           selected={field.value}
           onChange={(date) => field.onChange(date)}
        />
     )}
  />
}
Run Code Online (Sandbox Code Playgroud)

defaultValues 在自定义挂钩中的第一次渲染时缓存

javascript reactjs react-hook-form

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

Material UI 开关输入在表单重置时未更新

我正在用来react-hook-form构建我的表单,它是一个很棒的工具。但是,我似乎无法<Switch />根据 redux 的返回值让元素滑动(假/真)。当我单击表单上的“重置”时,我的所有输入都会重置。我的 Switch 控件不会重置,它们仍然停留在最后一个值,无论它是否可能被重置。关于如何解决这个问题有什么想法吗?

我的开关

<FormControlLabel
  control={
    <Switch
      size="medium"
      name="familyFriendly"
      defaultChecked={formState.content.isFamilySafe}
      {...register('content.isFamilySafe')}
    />
  }
  label="Family Friendly"
/>
Run Code Online (Sandbox Code Playgroud)

复位按钮

   <button
        type="button"
        onClick={() => {
          reset(formState, {
            keepErrors: true,
            keepDirty: true,
            keepIsSubmitted: false,
            keepTouched: false,
            keepIsValid: false,
            keepSubmitCount: false,
          });
        }}
      >
        reset
      </button>
Run Code Online (Sandbox Code Playgroud)

使用表单钩子

  const formState = useSelector(selectDynamicForm);
  const {
    register,
    control,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<IFormInput>({});
Run Code Online (Sandbox Code Playgroud)

reactjs material-ui react-hook-form

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

React Hook Form 和 React Select 未按预期工作

我试图Controller按照文档(https://react-hook-form.com/get-started#IntegratingControlledInputs)使用包装器组件将 React Select 包装在 React Hook Form 内

            <Controller
              name="ShiftCaptain"
              control={control}
              render={({ field }) => (
                <Select
                  {...field}
                  value={selectValue}
                  options={options}
                  placeholder={"Select Person"}
                  onChange={(e) => setSelectValue(e)}
                />
              )}
            />
Run Code Online (Sandbox Code Playgroud)

提交表单时,React Select 中捕获的值不会填充到 React Hook Forms 中: 在此输入图像描述

有任何想法吗?

TIA

reactjs react-select react-hook-form

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

React-hook-form:寄存器类型定义

我正在使用"react-hook-form": "^7.39.5"但无法弄清楚如何正确设置寄存器类型。

索引.tsx

const Index = () => {
  const {
    register,
    handleSubmit,
    formState: { errors },
    getValues,
    setValue,
  } = useForm<FormInputs>({
    resolver: yupResolver(formSchema),
  })
  const onSubmit = (data: FormInputs) => console.log(data)

  return(
  <FormInput
    label={label}
    register={{ ...register('firstName') }}
    errorMessage={errors['firstName']?.message}
   />
  )

  export default React.memo(Index)

}
Run Code Online (Sandbox Code Playgroud)

表单输入.tsx

type FormInputProps = {
  label: string
  register: any // <-- I NEED THIS TO BE TYPED
  errorMessage?: string
  type?: string
}

const FormInput = ({ label, register, errorMessage, type }: FormInputProps) => …
Run Code Online (Sandbox Code Playgroud)

typescript react-hook-form

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

使用react-hook-form手表计算字符数

目前,我正在使用react-hook-form进行表单传输。而且,我想渲染输入和文本区域中包含的字符数。

我实现的代码如下。

<input
  id="title"
  type="text"
  placeholder="title"
  {...register('title', {
    required: true,
  })}
/>
<span>
  {watch('title').length}/20
</span>

Run Code Online (Sandbox Code Playgroud)

如上所示,我尝试渲染通过watch输入的字符数,但失败了。你如何表示字符数?

watch reactjs react-hook-form

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

React-hooks-form 中的受控组件和非受控组件之间的主要区别是什么?

我正在使用反应钩子形式。我从有关受控和非受控的文档中读到。

受控

<form onSubmit={handleSubmit(onSubmit)}>
  <input name="firstName" ref={register({ required: true })} />
  <input name="lastName" ref={register} />
  <input type="reset" /> // standard reset button
  <input type="button" onClick={reset} />
  <input type="button" onClick={() => reset({ firstName: "bill" }); }} /> // reset form with values
  <input type="button" onClick={() => {
    reset({
      firstName: "bill"
    }, {
      errors: true, // errors will not be reset 
      dirtyFields: true, // dirtyFields will not be reset
      isDirty: true, // dirty will not be reset
      isSubmitted: false,
      touched: false,
      isValid: …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-hook-form

0
推荐指数
1
解决办法
6937
查看次数

支持使用 React Hook 表单验证时更改另一个字段值的回调

TL; 博士

这有效:https : //codesandbox.io/s/stoic-beaver-ucydi

使用 React Hook Form 重构后,这不起作用:https ://codesandbox.io/s/objective-cloud-bkunr?file=/src/ControlledTextField.tsx


很长的故事

没有 React Hook 表单(工作正常)

我最近使用Fluent UI构建了一个有状态的 React 表单,并将字段包装在自定义组件中。

我已经包含了一个功能,当您在站点标题字段中键入时,会生成站点 URL 字段中的值(在我的情况下,它只是复制字段值并删除对 URL 无效的字符)。

(简化的)代码运行良好,如下所示:

import * as React from 'react';
import {useState} from 'react';
import { PrimaryButton } from 'office-ui-fabric-react';
import SiteTitleField from '../../../common/formFields/SiteTitleField';
import SiteUrlField from '../../../common/formFields/SiteUrlField';

export default function MyForm(props) {

  const urlPrefix: string = "https://" + window.location.hostname + "/sites/";

  const [siteTitle, setSiteTitle] = useState();
  const [titleErrorMessage, setTitleErrorMessage] = useState('');

  const [siteUrl, …
Run Code Online (Sandbox Code Playgroud)

reactjs yup react-hooks react-hook-form fluentui-react

0
推荐指数
1
解决办法
3133
查看次数

面临 React-hook 表单的问题

我从 NB 3.0 复制/粘贴 React Hook Forms 的第一个示例并收到此错误。TypeError: 错误不是 Object。(评估错误中的“firstName”)。知道为什么吗?

react-native native-base react-hook-form

0
推荐指数
1
解决办法
760
查看次数

React Hook Form dirtyFields 返回不完整/缺失的应该是脏的字段

我的表单中的一个字段endTimeMins似乎没有注册到 formState。我有四个字段,所有字段都没有脏问题,我可以将它们读取为脏字段,但不能读取endTimeMins字段。其他信息,我正在使用 MUI v4 作为我的输入组件。

我以可重用的方式创建了输入字段。总的来说,它渲染了 4 个字段。

首先是我的 startTimeHour/endTimeHour。

   <Controller
      name={`${timeType}Hour`}
      control={control}
      rules={{ required: true, validate: () => _isEndGreaterThanStart() || errorMsgs.endNotGreater }}
      render={({ field: { onChange, value, name, onInputChange } }) => (
        <Controls.SingleAutoComplete
          name={`${timeType}Hour`}
          disableClearable
          freeSolo
          value={value.toString()}
          inputValue={value}
          className={classes.autoCompleteInput}
          error={!!errors[name]?.message}
          options={HOURS_OPTIONS.map((option) => option.value)}
          onChange={(e, newValue) => {
            onChange(newValue);
            _handleStartEndRelation(name, newValue);
          }}
          onInputChange={(e, newValue) => {
            onChange(handleTimeInputs(newValue, 12).toString()); //handle unwanted inputs
            _handleStartEndRelation(name, newValue);
          }}
        />
      )}
    />
Run Code Online (Sandbox Code Playgroud)

这是我的 startTimeMins/ endTimeMins

<Controller
      name={`${timeType}Mins`}
      control={control}
      rules={{ required: …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs material-ui react-hook-form

0
推荐指数
1
解决办法
7106
查看次数

未捕获的类型错误:e.preventDefualt 不是函数

我对 React 和 js 总体来说是新手,我正在学习 React 速成课程,并在课程中的某个时刻陷入了这个错误。这是我收到的错误消息是针对 PreventDefault 方法的,我用该方法来阻止页面刷新。

这是 2 个文件问题

import { useState } from "react"

export function NewTodoForm({onSubmit}){
    const [newItem, setNewItem] = useState("")
  function handleSubmit(e) {

    e.preventDefualt()
    if (newItem === "") return
    onSubmit(newItem)
    
    setNewItem("")
  }
return (
    <form className="new-item-form" onSubmit={handleSubmit}>
        <div className="form-row">
          <label htmlFor="item"> New Item</label>
          <input value={newItem} onChange={e => setNewItem(e.target.value)} type="text" id="item"></input>
        </div>
        <button className="btn" >
          Add
        </button>
      </form>
)
}
Run Code Online (Sandbox Code Playgroud)

import "./styles.css"
import { useState } from "react"
import { NewTodoForm } from "./NewTodoForm"

function …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-props react-functional-component react-hook-form

0
推荐指数
1
解决办法
108
查看次数