Reactjs 使用反应钩形式';如果我使用自定义组件而不是普通的HTML5输入标记,则s ref会在控制台中抛出错误

Reactjs 使用反应钩形式';如果我使用自定义组件而不是普通的HTML5输入标记,则s ref会在控制台中抛出错误,reactjs,react-hook-form,Reactjs,React Hook Form,今天我第一次尝试react-hook表单(到现在为止一直在使用formik)。根据文件,我跟踪了一切。仍然出现错误,如“无法为函数组件提供引用。尝试访问此引用将失败。是否要使用React.forwardRef()?”以及当我单击“提交”时,没有显示任何值HookFormControl'是一个自定义输入元素,已导入 import { useForm } from 'react-hook-form' import HookFormControl from '../forms/HookFormCont

今天我第一次尝试react-hook表单(到现在为止一直在使用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>
从'react hook form'导入{useForm}
从“../forms/HookFormControl”导入HookFormControl
常量{register,handleSubmit,errors,reset}=useForm()
const onSubmit=submittedData=>{console.log('submittedData=',submittedData)}
创造
  • 确保
    HookFormControl
    组件不公开输入的
    ref
  • // 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>
      </>
    ));
    
    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>
      );
    }