React hook 表单:如何在 React Hook Form 7.0 版上使用 onChange

IT技术 javascript reactjs react-hook-form
2021-05-04 09:20:45

以前我是这样写的:

<input className="form-control" name="productImage" type='file' onChange={handleImageUpload} ref={register({ required: true })} />

更新后我必须这样写:

<input className="form-control" type="file" {...register('productImage', { required: true })} />

如何onChange={handleImageUpload}在 React Hook Form 的更新版本上使用这是迁移文档

请原谅我在提问方式上的错误。我对这些东西很陌生。谢谢你。

4个回答

你只需要在之后移动onChangeprops{...register(...)}

const productImageField = register("productImage", { required: true });

return (
    <input
        className="form-control"
        type="file"
        {...productImageField}
        onChange={(e) => {
          productImageField.onChange(e);
          handleImageUpload(e);
     }}
    />
)

(2021 年 12 月 3 日)编辑:由于react-hook-form v7.16.0 的更改此方法不再正确,请参阅@Bill的回答。

https://github.com/react-hook-form/react-hook-form/releases/tag/v7.16.0

V7.16.0 为自定义onChange.

<input
  type="text"
  {...register('test', {
    onChange: (e) => {},
    onBlur: (e) => {},
  })}
/>

register文档https://react-hook-form.com/api/useform/register 中,示例存在于Custom onChange, onBlur部分:

// onChange got overwrite by register method
<input onChange={handleChange} {...register('test')} />

// register's onChange got overwrite by register method
<input {...register('test')} onChange={handleChange}/>

const firstName = register('firstName', { required: true })
<input 
  onChange={(e) => {
    firstName.onChange(e); // method from hook form register
    handleChange(e); // your method
  }}
  onBlur={firstName.onBlur}
  ref={firstName.ref} 
/>

所以对于你的情况:

const productImageRegister = register("productImage", {required: true})
<input className="form-control"
       type="file"
       {...productImageRegister }
       onChange={e => {
           productImageRegister.onChange(e);
           handleImageUpload(e);
       }} />

对我来说,装修解决方案奏效了

const fieldRegister = register("productImage", {required: true})
const origOnChange = fieldRegister.onChange
fieldRegister.onChange = (e) => {
    const res = origOnChange(e)
    const value = e.target.value
    // do something with value
    return res
}

对于字段声明使用

<input {...fieldRegister}/>