1

I'm working on a React project using TypeScript and react-hook-form. In some place I use the given function register() that have to be used like that (according to the official documentation):

<input
  name="test"
  ref={
    register({
      required: true
    })
  }
/>

The problem I'm facing here is that this function is typed in such a way that it return void:

(Ref, validateRule?) => void

But the attribute ref of the native input tag has to be of type:

string | ((instance: HTMLInputElement | null) => void) | RefObject<HTMLInputElement> | null | undefined

So naturally TypeScript throws me this error:

Type 'void' is not assignable to type 'string | ((instance: HTMLInputElement | null) => void) | RefObject | null | undefined'

Do you have an idea of how I can use this library while respecting the types? Is this a mistake on the part of the library itself?

4

1 回答 1

1

I found already solved answers on the Github related project : https://github.com/react-hook-form/react-hook-form/issues?q=is%3Aissue+is%3Aclosed+register+void+is+not+assignable+to+type

Looks like depending on what you plug on the ref prop. Maybe consider init this on a useEffect ?

Refer to this issue : https://github.com/react-hook-form/react-hook-form/issues/598 redirect himself to the documentation for Controlled components (could be your case). You should probably use the useEffect way like :

const Comp = () => {
  const { register } = useForm()

  React.useEffect(() => {
    register({ name: "nameOfMyInput" })
  })

  return (
    <input name="nameOfMyInput" />
  )
}
于 2020-04-08T08:36:07.173 回答