【问题标题】:onChange input in react-hook-form以 react-hook-form 的 onChange 输入
【发布时间】:2023-03-17 10:12:01
【问题描述】:

我正在使用 React 和 react-hook-form 库构建 webapp。我想创建表单,其中某些字段的更改会触发某些事件。所以我需要通过自定义onChange

但是,从 v7.0 开始,我无法使用 onChange,因为 register 使用了自己的 onChange

import React from 'react'
import { useForm } from 'react-hook-form'

const MyForm = () => {

  const form = useForm()
  const onChangeFirst = value => console.log('First:', value)
  const onChangeSecond = value => console.log('Second:', value)

  return (
    <form onSubmit={form.handleSubmit(vals => null)}>
      <input {...register('first')} />
      <input {...register('second')} />
    </form> 
  )

}

如何将onChangeFirst 传递给first 输入并将onChangeFirst 传递给second 输入?

【问题讨论】:

    标签: javascript reactjs forms react-hook-form


    【解决方案1】:

    有两种方法可以在输入更改时触发onChange

    1/ 带有Controller 组件(推荐)

    const onChangeFirst = value => console.log('First:', value)
    
    <Controller
      control={control}
      name="first"
      render={({field}) => (
        <input {...field} onChange={e => {
          onChangeFirst(field.value);
          field.onChange(e);
        }} />
      )}
    />
    

    2/ 带有useWatch钩子

     const second = useWatch({
        control,
        name: 'second'
     });
    
     useEffect(() => {
       console.log('Second:', second)
     }, [second])
    

    【讨论】:

      猜你喜欢
      • 2022-06-13
      • 2021-12-09
      • 1970-01-01
      • 2021-10-05
      • 1970-01-01
      • 2022-07-30
      • 2023-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多