React hook form v7 Function 组件不能被赋予引用。尝试访问此引用将失败。你的意思是使用 React.forwardRef()

时间:2021-06-07 19:49:53

标签: reactjs typescript ref

在浏览器中出现错误 Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()

enter image description here

我的代码:

import { yupResolver } from '@hookform/resolvers/yup'
import { useState } from 'react'
import { SubmitHandler, useForm } from 'react-hook-form'
import { contactSchema } from 'schemas/schemas'
import { InputFloatLabel } from './components/Inputs/InputFloatLabel'

type TypeFormInput = {
  name: string
  email: string
  textarea: string
}

export const Register = () => {
  const [isLoading, setIsLoading] = useState(false)

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<TypeFormInput>({ resolver: yupResolver(contactSchema) })

  const onSubmit: SubmitHandler<TypeFormInput> = async ({ name, email }) => {
    console.log('? ~ file: Register.tsx ~ line 25 ~ email', email)
    console.log('? ~ file: Register.tsx ~ line 25 ~ name', name)
  }


  return (
    <div>
      <form onSubmit={handleSubmit(onSubmit)}>
        <div>
          <InputFloatLabel
            type="text"
            placeholder="Name"
            {...register('name')}
          />

          <button type="submit">{isLoading ? 'Loading' : 'Send Mail'}</button>
        </div>
      </form>
    </div>
  )
}

和输入组合:

import { useState } from 'react'

type typeInput = {
  placeholder: string
  type?: string
}

export const InputFloatLabel: React.FC<typeInput> = ({ type, placeholder, ...props }) => {
  const [isActive, setIsActive] = useState(false)

  const handleTextChange = (text: string) => {
    if (text !== '') setIsActive(true)
    else setIsActive(false)
  }

  return (
    <div>
      <input
        {...props}
        id={placeholder}
        type={placeholder ? placeholder : 'text'}
        onChange={(e) => handleTextChange(e.target.value)}
      />
      <label htmlFor={placeholder}>
        {placeholder ? placeholder : 'Placeholder'}
      </label>
    </div>
  )
}

我构建的 ChakraUI 没有这个问题,但现在只是将普通输入作为一个单独的组件来解决这个问题。

我尝试了这里的一些建议,但仍然无法解决:https://github.com/react-hook-form/react-hook-form/issues/85

1 个答案:

答案 0 :(得分:0)

您的输入组件不会将 ref 导出为 props,因为它是一个功能组件。

 React.useEffect(() => {
    register('name', { required: true });
  }, []);

         <InputFloatLabel
            type="text"
            placeholder="Name"
            name="name"
           // Remove the register from here
          />