使用useRef获取联系表单数据时触发Hook规则报错如何修复?
错误根因
你触发的react-hooks/rules-of-hooks规则报错,核心原因有两点:
- React Hook 必须在函数组件顶层作用域调用,不能在事件回调、循环、条件判断等非顶层场景执行,你将
useRef写在handleSubmit提交回调里属于违规用法 - 函数组件不存在类组件的
this指向,你在JSX中写的inputRef={this.name}这类绑定写法完全无效
修复步骤
- 将三个字段对应的
useRef声明移到Form组件的顶层作用域,不能放在handleSubmit内部 - 将TextField组件的
inputRef属性绑定到对应的ref变量,删除this.前缀,同时修改三个TextField的重复id避免DOM冲突 - 提交时直接从ref的
current属性获取DOM节点,再读取对应value
修复后完整代码
import React, { useState, useRef } from "react"; import { makeStyles } from "@material-ui/core/styles"; import TextField from "@material-ui/core/TextField"; import Button from "@material-ui/core/Button"; const useStyles = makeStyles((theme) => ({ root: { "& > *": { margin: theme.spacing(1), width: "25ch", }, }, })); const Form = () => { const classes = useStyles(); const [status, setStatus] = useState("Submit"); // 顶层定义三个字段的ref const nameRef = useRef(null); const emailRef = useRef(null); const messageRef = useRef(null); const handleSubmit = async (e) => { e.preventDefault(); setStatus("Sending..."); let details = { name: nameRef.current.value, email: emailRef.current.value, message: messageRef.current.value, }; let response = await fetch("http://localhost:5000/contact", { method: "POST", headers: { "Content-Type": "application/json;charset=utf-8", }, body: JSON.stringify(details), }); setStatus("Submit"); let result = await response.json(); alert(result.status); }; return ( <div> <form className={classes.root} onSubmit={handleSubmit}> <TextField type="text" style={{ color: "white" }} inputRef={nameRef} id="standard-basic-name" label="Name" /> <TextField inputRef={emailRef} required type="email" style={{ color: "white" }} id="standard-basic-email" label="Email" /> <TextField inputRef={messageRef} type="text" style={{ color: "white" }} id="standard-basic-message" label="Message" required /> <Button type="submit" id="contacts1" color="primary"> {status} </Button> </form> </div> ); }; export default Form;
内容的提问来源于stack exchange,提问作者Asrorbek
相关产品推荐
相关产品推荐

