英文:
Showing form errors only when clicking submit button in react
问题
以下是您的代码的翻译部分:
我有这个React组件,它渲染了一个简单的登录功能,错误验证在单独的文档中进行,而在编写时,如果有错误,它会被渲染出来,但我希望它们只在我点击提交按钮时才渲染,我在这里已经呆了一整天,但仍然找不到解决方案 >.< 这是我第一次使用这个平台,如果可能的话,不要给我具体的解决方案,而是给我一些启发,我想看看我是否能够自己做出来。
英文:
I have this react component that renders a simple log in funcionality, error validation is in a document apart, and while writing if there is an error it will render, but i want them to render only when i click the submit button, i've been the entire day here and still cannot find the solution >.< first time using this platform tho
if possible dont bring me the exact solution but enlighten my mind i'd like to see if i can make it myself
import { useState } from "react"
import validations from "./validations"
function Form({login}) {
const [errors, setErrors] = useState({})
const [userData, setUserData] = useState({
email: '',
password: ''
})
const handlechange = (event)=>{
setUserData({
...userData,
[event.target.name]: event.target.value
})
setErrors(validations({
...userData,
[event.target.name]: event.target.value
}))
}
const handleSubmit = (event)=>{
event.preventDefault()
login(userData)
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="pmail">Email:</label>
<input
type="email"
name='email'
input ={userData.email}
onChange={handlechange}
/>
{errors.email && <p>{errors.email}</p>}
<label htmlFor="password">Password:</label>
<input
type="password"
name="password"
input={userData.password}
onChange={handlechange}
/>
{errors.password && <p>{errors.password}</p>}
<button>Log In</button>
</form>
)
}
export default Form
答案1
得分: 1
你在handlechange()
中每次都设置了error
,因此错误会在状态更改时渲染出来。如果你只在onSubmit
时验证并设置错误,那么只有在实际提交表单时才会渲染错误信息。
以下是基于你的代码的示例实现。尝试使用evil@hacker.com
登录并输入任何密码,然后查看提交表单时错误信息的渲染。
function validations(user) {
if (user.email.toLowerCase() === "evil@hacker.com") {
return { email: "Hackers are not allowed here!" }
}
return {};
}
function login(user) {
console.log(`Successfully logged in user ${user.email}`);
}
function isEmpty(obj) {
for (let i in obj) return false;
return true;
}
function Form() {
const [errors, setErrors] = React.useState({})
const [userData, setUserData] = React.useState({
email: '',
password: ''
})
const handlechange = (event) => {
setUserData({
...userData,
[event.target.name]: event.target.value
})
}
const handleSubmit = (event) => {
event.preventDefault()
const validationResult = validations(userData);
if (isEmpty(validationResult)) {
// no errors
setErrors({})
login(userData);
}
else {
console.log(`Access denied for ${userData.email}`);
setErrors(validationResult);
}
}
return (
<form onSubmit={handleSubmit} className="form">
<label htmlFor="email">Email:</label>
<input
type="email"
name='email'
value={userData.email}
onChange={handlechange}
/>
{errors.email && <p>{errors.email}</p>}
<label htmlFor="password">Password:</label>
<input
type="password"
name="password"
value={userData.password}
onChange={handlechange}
/>
{errors.password && <p>{errors.password}</p>}
<button>Log In</button>
</form>
)
}
ReactDOM.render(<Form />, document.getElementById('root'));
希望这对你有所帮助。
英文:
You set the error
every time in handlechange()
so the errors are rendered as the state has changed. If you only validate onSubmit
and set the errors there they will only be rendered when you actually submit the form.
Here a sample implementation based on your code. Try to login with evil@hacker.com
and any password to see errors getting rendered when you submit the form.
<!-- begin snippet: js hide: false console: true babel: true -->
<!-- language: lang-js -->
function validations(user) {
if (user.email.toLowerCase() === "evil@hacker.com") {
return { email: "Hackers are not allowed here!" }
}
return {};
}
function login(user) {
console.log(`Successfully logged in user ${user.email}`);
}
function isEmpty(obj) {
for (let i in obj) return false;
return true;
}
function Form() {
const [errors, setErrors] = React.useState({})
const [userData, setUserData] = React.useState({
email: '',
password: ''
})
const handlechange = (event) => {
setUserData({
...userData,
[event.target.name]: event.target.value
})
}
const handleSubmit = (event) => {
event.preventDefault()
const validationResult = validations(userData);
if (isEmpty(validationResult)) {
// no errors
setErrors({})
login(userData);
}
else {
console.log(`Access denied for ${userData.email}`);
setErrors(validationResult);
}
}
return (
<form onSubmit={handleSubmit} class="form">
<label htmlFor="email">Email:</label>
<input
type="email"
name='email'
input={userData.email}
onChange={handlechange}
/>
{errors.email && <p>{errors.email}</p>}
<label htmlFor="password">Password:</label>
<input
type="password"
name="password"
input={userData.password}
onChange={handlechange}
/>
{errors.password && <p>{errors.password}</p>}
<button>Log In</button>
</form>
)
}
ReactDOM.render(<Form />, document.getElementById('root'));
<!-- language: lang-css -->
.form {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
<!-- language: lang-html -->
<script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<div id="root"></div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论