【发布时间】:2022-01-01 06:52:00
【问题描述】:
我想在用户单击提交表单按钮时从用户那里获取输入数据。单击时,我得到一个响应对象,其中显示了屏幕截图中的空值。据我了解,我不想要 useState 因为它会使页面重新渲染,我不想要那样。这是我第一次使用 useRef,有什么我遗漏的吗?
import Box from "@mui/material/Box";
import Grid from "@mui/material/Grid";
import Typography from "@mui/material/Typography";
import TextField from "@mui/material/TextField";
import Button from "@mui/material/Button";
import { useRef } from "react";
const ContactSection = () => {
let nameRef = useRef(null); // name
let emailRef = useRef(null); // email
let messageRef = useRef(null); // message
const formSubmit = (event) => {
event.preventDefault();
const data = {
name: nameRef.current.value,
email: emailRef.current.value,
message: messageRef.current.value,
};
console.log(data);
};
return (
<Box component="form">
<TextField
ref={nameRef}
type="text"
id="form-name"
label="Name"
sx={{ mt: 2 }}
></TextField>
<TextField
ref={emailRef}
type="email"
id="form-email"
label="Email"
sx={{ mt: 2 }}
></TextField>
<TextField
ref={messageRef}
type="text"
id="form-msg"
label="Message"
multiline
rows={5}
sx={{ mt: 2 }}
></TextField>
</Box>
<Button
variant="contained"
onClick={formSubmit}
sx={{
mt: 4,
"&:hover": {
color: "secondary.main",
transition: "ease-in 0.2s",
transform: "scale(1.05)",
},
}}
>
Submit
</Button>
);
};
export default ContactSection;
触发表单提交句柄时,我在控制台中收到此错误
【问题讨论】:
-
为什么 useRef... ref 用于在组件的所有生命周期中保持相同的状态。对于需要使用
useState的表单。创建具有状态的对象并在文本字段上使用 onChange 方法来更新状态
标签: reactjs material-ui