reactjs - 如果我使用自定义组件而不是普通的 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>
解决方案
- 确保该
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>
</>
));
- 你可以
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>
);
}
推荐阅读
- javascript - 我需要比较给定数组元素的时间戳,并根据 JavaScript 中的比较将这些元素推送到新数组
- python - 在 ViT 模型的转换器中,last_hidden_state 不等于 hidden_states[-1]
- fpga - Lattice Mach XO2 内部时钟利用率
- oracle - 在 Oracle 12c 的 WHERE 子句中使用 CASE
- javascript - iPhone 上的 Javascript 触控力
- python - 没有ansi颜色代码的Python pexpect模式匹配不起作用
- git - GIT 在本地分支上进行远程修改
- google-play - 如何退出 Google Play 的亲子同乐计划?
- node.js - 如何为特定令牌、颤振、firebase 消息传递和 node.js 发送通知
- android-recyclerview - 将图像绑定到recyclerview时毕加索出现问题