我开始我的第一个react.js,下面的代码创建两个表单(登录和注册)。输入"电子邮件"one_answers"密码"很顺利,而输入"firstName"one_answers"lastName"则没有任何作用。
我已经创建了一个名为'FormField'的组件,它是一个简单的输入文本字段。
大概是在上下传递道具和状态时丢失了一些东西,这似乎是一个常见的问题。但是我被难住了——我看不出少了什么。
app/线路/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>
);
}
在初始状态中,您使用的是firstname和lastname,但是在handleInputChange函数中,您使用的是firstname和lastname来更新状态。
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,
}));