在React中,仅在单击提交按钮时显示表单错误。

huangapple go评论77阅读模式
英文:

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 &quot;react&quot;
import validations from &quot;./validations&quot;

function Form({login}) {
    const [errors, setErrors] = useState({})
    const [userData, setUserData] = useState({
        email: &#39;&#39;,
        password: &#39;&#39;
    })

    const handlechange = (event)=&gt;{
        setUserData({
            ...userData,
            [event.target.name]: event.target.value
        })

        setErrors(validations({
            ...userData,
            [event.target.name]: event.target.value
        }))
    }

    const handleSubmit = (event)=&gt;{
        event.preventDefault()
        login(userData)
    }

  return (
    &lt;form onSubmit={handleSubmit}&gt;
        &lt;label htmlFor=&quot;pmail&quot;&gt;Email:&lt;/label&gt;
            &lt;input 
                type=&quot;email&quot; 
                name=&#39;email&#39;
                input ={userData.email}
                onChange={handlechange}
            /&gt;

            {errors.email &amp;&amp; &lt;p&gt;{errors.email}&lt;/p&gt;}

        &lt;label htmlFor=&quot;password&quot;&gt;Password:&lt;/label&gt;
            &lt;input 
                type=&quot;password&quot;
                name=&quot;password&quot; 
                input={userData.password}
                onChange={handlechange}
            /&gt;

            {errors.password &amp;&amp; &lt;p&gt;{errors.password}&lt;/p&gt;}
            
        &lt;button&gt;Log In&lt;/button&gt;

    &lt;/form&gt;
  )
}
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() === &quot;evil@hacker.com&quot;) {
return { email: &quot;Hackers are not allowed here!&quot; }
}
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: &#39;&#39;,
password: &#39;&#39;
})
const handlechange = (event) =&gt; {
setUserData({
...userData,
[event.target.name]: event.target.value
})
}
const handleSubmit = (event) =&gt; {
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 (
&lt;form onSubmit={handleSubmit} class=&quot;form&quot;&gt;
&lt;label htmlFor=&quot;email&quot;&gt;Email:&lt;/label&gt;
&lt;input
type=&quot;email&quot;
name=&#39;email&#39;
input={userData.email}
onChange={handlechange}
/&gt;
{errors.email &amp;&amp; &lt;p&gt;{errors.email}&lt;/p&gt;}
&lt;label htmlFor=&quot;password&quot;&gt;Password:&lt;/label&gt;
&lt;input
type=&quot;password&quot;
name=&quot;password&quot;
input={userData.password}
onChange={handlechange}
/&gt;
{errors.password &amp;&amp; &lt;p&gt;{errors.password}&lt;/p&gt;}
&lt;button&gt;Log In&lt;/button&gt;
&lt;/form&gt;
)
}
ReactDOM.render(&lt;Form /&gt;, document.getElementById(&#39;root&#39;));

<!-- language: lang-css -->

.form {
display: flex;
flex-direction: column;
gap: 0.25rem;
}

<!-- language: lang-html -->

&lt;script crossorigin src=&quot;https://unpkg.com/react@18/umd/react.production.min.js&quot;&gt;&lt;/script&gt;
&lt;script crossorigin src=&quot;https://unpkg.com/react-dom@18/umd/react-dom.production.min.js&quot;&gt;&lt;/script&gt;
&lt;div id=&quot;root&quot;&gt;&lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月7日 05:22:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76191212.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定