简体   繁体   English

react-form-hook 的自定义输入不起作用

[英]Custom input from react-form-hook not working

Following the example here I have a custom input component:按照此处的示例,我有一个自定义输入组件:

Input.tsx输入.tsx

import React from "react";

export default function Input({label, name, onChange, onBlur, ref}:any) {

    return (
        <>
        <label htmlFor={name}>{label}</label>
        <input
          name={name}
          placeholder="Jane"
          onChange={onChange}
          onBlur={onBlur}
          ref={ref}
        />
      </>
    );
}

An example of the usage:使用示例:

import {useAuth} from '../components/AuthContextProvider'
import { useForm, SubmitHandler } from "react-hook-form";
import Input from '../components/Input'


function Subscriptions({ Component, pageProps }: any) {
  const { user  } = useAuth()
  const { register, handleSubmit, formState: { errors } } = useForm<Inputs>();

  const onSubmit: SubmitHandler<Inputs> = async data => {
    console.log(data, 'data sdfdsg')
  }


  return (
    <>
      <form onSubmit={handleSubmit(onSubmit)}>
        <Input label="name" {...register('name')}/>
        <button type='submit'>Add kid</button>
      </form>
    </>
    )
}

export default Subscriptions

Here's my package version:这是我的 package 版本:

"react-hook-form": "^7.34.2"

Any ideas what I'm doing wrong here?有什么想法我在这里做错了吗?

The custom input receives undefined but it works with normal <input /> tags.自定义输入接收未定义,但它适用于普通<input />标签。

I've used the example in a codesandbox and it threw errors about ref and it suggested using React.forwardRef , change your custom Input to this:我在代码框中使用了该示例,它引发了有关ref的错误,并建议使用React.forwardRef ,将您的自定义输入更改为:

function Input({ label, name, onChange, onBlur }, ref) {
  return (
    <>
      <label htmlFor={name}>{label}</label>
      <input
        name={name}
        placeholder="Jane"
        onChange={onChange}
        onBlur={onBlur}
        ref={ref}
      />
    </>
  );
}

const MyInput = React.forwardRef(Input);

export default MyInput;

and by the way, ref is not part of props I don't know why the example has it like that, it's necessary to use forwardRef so it is passed as second argument.顺便说一句, ref不是props的一部分我不知道为什么这个例子有这样的,有必要使用forwardRef所以它作为第二个参数传递。

you can see the full example in this codesandbox你可以在这个代码框里看到完整的例子

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

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