繁体   English   中英

以 react-hook-form 的 onChange 输入

[英]onChange input in react-hook-form

我正在使用 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输入?

有两种方法可以在输入更改时触发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])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM