我正在开始我的第一部分 react.js,下面的代码创建了两种形式(登录和注册)。在输入文本“电子邮件”和“密码”中键入顺利,而在“名字”和“姓氏”字段中键入没有任何作用。
我创建了一个名为“FormField”的组件,它是一个简单的输入文本字段。
据推测,上下传递 props 和 state 时缺少某些东西,这似乎是一个普遍的问题。但我很难过 - 我看不出缺少什么。
app/routes/login.tsx
import { Layout } from "~/components/layout";
import { FormField } from "~/components/form-field";
import { useState } from "react";
import { ActionFunction, json } from "@remix-run/node";
import { login, register } from "~/utils/auth.server";
export default function Login() {
const [action, setAction] = useState("login");
const [formData, setFormData] = useState({
email: "",
password: "",
firstname: "",
lastname: "",
});
// Updates the form data when an input changes
const handleInputChange = (
event: React.ChangeEvent<HTMLInputElement>,
field: string
) =>
setFormData((form) => ({
...form,
[field]: event.target.value,
}));
return (
<Layout>
<div className="h-full flex justify-center items-center flex-col gap-y-4">
<button
onClick={() => setAction(action == "login" ? "register" : "login")}
className="absolute top-8 right-8 rounded-xl bg-yellow-300 font-semibold text-blue-600 px-3 py-2 translate duration-300 ease-in-out hover:bg-yellow-400 hover:-translate-y-1"
>
{action === "login" ? "Sign Up" : "Sign In"}
</button>
<h2 className="text-5xl font-extrabold text-yellow-400">
Welcome to focus!
</h2>
<p className="font-semibold text-slate-300">
{action === "login" ? "Log In" : "Sign Up"}
</p>
<form method="post" className="rounded-2xl bg-gray-200 p-6 w-96">
<FormField
htmlFor="email"
label="Email"
value={formData.email}
onChange={(e) => handleInputChange(e, "email")}
/>
<FormField
htmlFor="password"
label="Password"
type="password"
value={formData.password}
onChange={(e) => handleInputChange(e, "password")}
/>
{action !== "login" ? (
<>
<FormField
htmlFor="firstName"
label="First Name"
value={formData.firstname}
onChange={(e) => handleInputChange(e, "firstName")}
/>
<FormField
htmlFor="lastName"
label="Last Name"
value={formData.lastname}
onChange={(e) => handleInputChange(e, "lastName")}
/>
</>
) : null}
<div className="m-full text-center">
<button
type="submit"
name="_action"
value={action}
className="rounded-xl mt-2 bg-yellow-300 px-3 py-2 text-blue-600 font-semibold transition duration-300 ease-in-out hover:bg-yellow-400 hover:-translate-y-1"
>
{action === "login" ? "Sign In" : "Sign Up"}
</button>
</div>
</form>
</div>
</Layout>
);
}
在初始状态下,您使用名字和姓氏,但在 handleInputChange 函数中,您使用名字和姓氏更新状态。
const [formData, setFormData] = useState({
email: "",
password: "",
firstname: "",
lastname: "",
});
JavaScript 区分大小写。因此,当您在 firstName 和 lastName 字段中键入时,formData 状态不会更新。
要解决此问题,您可以更新初始状态以使用 firstName 和 lastName 而不是 firstname 和 lastname:
const [formData, setFormData] = useState({
email: "",
password: "",
firstName: "",
lastName: "",
});
或者,您可以在像这样进行比较之前将所有键都设为小写。
const handleInputChange = (
event: React.ChangeEvent<HTMLInputElement>,
field: string
) =>
setFormData((form) => ({
...form,
[field.toLowerCase()]: event.target.value,
}));