所以我試圖在React JS中做我的第一個項目。我正在用很少的基本輸入制作一個注冊屏幕。
以下是我的RegisterScreen.js文件:
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import {
MDBBtn,
MDBContainer,
MDBCard,
MDBCardBody,
MDBCol,
MDBRow,
MDBInput,
} from "mdb-react-ui-kit";
import axios from "axios";
import ErrorMessage from "../../Components/ErrorMessage";
import Loading from "../../Components/Loading";
const RegisterScreen = () => {
const navigate = useNavigate();
const [email, setEmail] = useState("");
const [name, setName] = useState("");
const [pic, setPic] = useState("");
const [picMessage, setPicMessage] = useState("");
const [password, setPassword] = useState("");
const [message, setMessage] = useState(false);
const [error, setError] = useState(false);
const [loading, setLoading] = useState(false);
const [cnfrmPassword, setCnfrmPassword] = useState(false);
const navFun = () => {
navigate("/mynotes");
};
const SaveHandler = async (e) => {
e.preventDefault();
console.log(name, email, password, cnfrmPassword);
if (password !== cnfrmPassword) {
setLoading(true);
setTimeout(() => {
setMessage("Passwords do not match");
setLoading(false);
}, 500);
setTimeout(() => {
setMessage(null);
}, 2500);
} else {
setMessage(null);
try {
const config = {
headers: {
"Content-type": "application/json",
},
};
setLoading(true);
const { data } = await axios.post(
"/api/users",
{ name, email, password, pic },
config
);
localStorage.setItem("userInfo", JSON.stringify(data));
navFun();
} catch (error) {
setError(error.response.data);
} finally {
setLoading(false);
}
}
};
const postDetails = (pics) => {
if (!pics) {
return setPicMessage("Please Select an Image");
} else {
setPicMessage(null);
}
if (
pics.type === "image/jpeg" ||
pics.type === "image/png" ||
pics.type === "image/JPEG" ||
pics.type === "image/PNG"
) {
const data = new FormData();
data.append("file", pics);
data.append("upload_preset", "noteApp");
data.append("cloud_name", "dbuwj7uyu");
fetch("https://api.cloudinary.com/v1_1/dbuwj7uyu/image/upload", {
method: "post",
body: data,
})
.then((res) => res.json())
.then((data) => {
console.log(data);
setPic(data.url.toString());
})
.catch((err) => {
console.log(err);
});
} else {
return setPicMessage("Please Select an Image");
}
};
return (
<MDBContainer fluid>
<MDBRow className="d-flex justify-content-center align-items-center h-100">
<MDBCol col="12">
<MDBCard
className="bg-white my-3 mx-auto"
style={{ borderRadius: "1rem", maxWidth: "500px" }}
>
<MDBCardBody className="px-5 py-3 w-100 d-flex flex-column">
<h2 className="fw-bold mb-0 text-center heading">SignUp</h2>
{message && (
<ErrorMessage variant="danger">{message}</ErrorMessage>
)}
{error && <ErrorMessage variant="danger">{error}</ErrorMessage>}
{loading && <Loading />}
<MDBInput
wrapperClass="mb-4 w-100"
placeholder="Full Name"
id="formControlLgFullName"
type="text"
size="lg"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<MDBInput
wrapperClass="mb-4 w-100"
placeholder="Email address"
id="formControlLgEmail"
type="email"
size="lg"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<MDBInput
wrapperClass="mb-4 w-100"
placeholder="Password"
id="formControlLgPwd"
type="password"
size="lg"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<MDBInput
wrapperClass="mb-4 w-100"
placeholder="Confirm Password"
id="formControlLgCpwd"
type="password"
size="lg"
value={cnfrmPassword}
onChange={(e) => setCnfrmPassword(e.target.value)}
/>
{picMessage && (
<ErrorMessage variant="danger">{picMessage}</ErrorMessage>
)}
<div className="uploadBtn">
<label className="p-2 pictureUpld">
Upload Profile Picture
</label>
<input
type="file"
// style={{ width: "95px" }}
className="lefftt py-2"
title=" "
onChange={(e) => postDetails(e.target.files[0])}
/>
</div>
<MDBBtn size="lg" onClick={SaveHandler}>
Submit
</MDBBtn>
<hr className="my-4" />
<div style={{ display: "inline-flex" }}>
<a href="/login" className="hyperlink">
Already Have an account?
</a>
</div>
</MDBCardBody>
</MDBCard>
</MDBCol>
</MDBRow>
</MDBContainer>
);
};
export default RegisterScreen;
CSS如下所示:
width: 50%;
margin-left: 35px;
text-align: right;
position: relative;
}
.uploadBtn {
padding: py-5;
display: "inline-flex";
border: #dddddd solid 2px;
border-radius: 0.5rem;
margin-bottom: 20px;
}
.pictureUpld {
text-align: center;
color: #868585;
}
除了確認密碼字段之外,一切正常。它顯示false(如*****),而不是在頁面加載時顯示占位符。以下是頁面加載時的圖像(1)和我手動清除后的圖像(2)
我檢查了一下,刪除value={cnfrmPassword}或將其設置為null確實有效。但是我不知道我應該怎么做
可以將confrmPassword初始化為空字符串而不是null,以顯示占位符值。
讓React管理表單組件值狀態的模式稱為受控組件(與不受控組件相反,如果您不設置值,而是讓輸入在內部管理它)。受控組件可能是一種有用的模式,因為它們確保了在整個應用程序生命周期中的穩定值。不受控制的組件更容易與父組件一起使用,配置也更簡單,但靈活性較差。
參見React文檔,了解受控和非受控組件之間的權衡:
https://react . dev/learn/sharing-state-between-components #受控和非受控組件
有關受控組件模式的更多信息,請參見此處:
https://blog . log rocket . com/controlled-vs-uncontrolled-components-in-react/