首页 > 解决方案 > 如果我使用自定义组件而不是普通的 HTML5 输入标签,使用 react-hook-form 的 ref 会在控制台中引发错误

问题描述

我今天第一次尝试 react-hook-form (直到现在都在使用 formik)。我已经按照文档进行了所有操作。仍然收到错误提示“无法为函数组件提供参考。尝试访问此参考将失败。您是要使用 React.forwardRef() 吗?” 而且当我点击提交时,没有任何价值被显示出来。'HookFormControl' 是一个自定义输入元素,已导入。

import { useForm } from 'react-hook-form'
import HookFormControl from '../forms/HookFormControl'

const { register, handleSubmit, errors, reset } = useForm()
const onSubmit = submittedData => { console.log('submittedData = ', submittedData) }

<form onSubmit={handleSubmit(onSubmit)}>
 <div className='row'>
  <div className='col-12'>
    <HookFormControl type='text' label='Site Name *' name='site' ref={register({required: true})} />
  </div>
 </div>

<div className='row'>
  <div className='col-12'>
    <button type='submit'>Create</button>
  </div>
 </div>
</form>

标签: reactjsreact-hook-form

解决方案


  1. 确保该HookFormControl组件确实公开了输入ref

https://react-hook-form.com/get-started#Integratinganexistingform

// you can use React.forwardRef to pass the ref too
const Select = React.forwardRef(({ label }, ref) => ( 
  <>
    <label>{label}</label>
    <select name={label} ref={ref}>
      <option value="20">20</option>
      <option value="30">30</option>
    </select>
  </>
));
  1. 你可以Controller用来包装你的受控组件

https://react-hook-form.com/get-started#IntegratingControlledInputs

import React from "react";
import { useForm, Controller } from "react-hook-form";
import ReactSelect from "react-select";
import { TextField, Checkbox } from "@material-ui/core";

function App() {
  const methods = useForm();
  const { handleSubmit, control, reset } = methods;
  const onSubmit = data => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {/* Option 1: pass a component to the Controller. */}
      <Controller as={TextField} name="TextField" control={control} defaultValue="" />
      
      {/* Option 2: use render props to assign events and value */}
      <Controller
        name="MyCheckbox"
        control={control}
        defaultValue={false}
        rules={{ required: true }}
        render={props =>
          <Checkbox
            onChange={e => props.onChange(e.target.checked)}
            checked={props.value}
          />
        } // props contains: onChange, onBlur and value
      />
    </form>
  );
}

推荐阅读