我想在用戶單擊提交表單按鈕時從用戶那里獲取輸入資料。單擊時,我得到一個回應物件,螢屏截圖中顯示了空值。據我了解,我不想要 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;
觸發 formSubmit 句柄時,我在控制臺中收到此錯誤

uj5u.com熱心網友回復:
使用 MUI TextField 時將 ref 更改為 inputRef
<Box component="form">
<TextField
inputRef={nameRef}
type="text"
id="form-name"
label="Name"
sx={{ mt: 2 }}
></TextField>
<TextField
inputRef={emailRef}
type="email"
id="form-email"
label="Email"
sx={{ mt: 2 }}
></TextField>
<TextField
inputRef={messageRef}
type="text"
id="form-msg"
label="Message"
multiline
rows={5}
sx={{ mt: 2 }}
></TextField>
</Box>
這將在控制臺日志中給出正確的輸出
uj5u.com熱心網友回復:
您必須使用inputRef而不是ref更多資訊,請參閱官方檔案。https://mui.com/api/text-field/
uj5u.com熱心網友回復:
對材質 UI 文本欄位組件使用 inputRef 而不是 ref 。參考:https : //mui.com/components/text-fields/#main-content
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/399845.html
上一篇:LOGINSERVICE.LoginWebServiceSoapClient未初始化并導致System.ServiceModel.CommunicationObjectFaultedException
下一篇:動態洗掉元素
