目录 Form数据管理 重置Form状态 form验证 小结 Form数据管理 有时会遇到多个位置需要用户输入的情况,若每个状态都配置state或handler会很繁琐,可以尝试下面的方法 import * as React from 'r
目录
- Form数据管理
- 重置Form状态
- form验证
- 小结
Form数据管理
有时会遇到多个位置需要用户输入的情况,若每个状态都配置state或handler会很繁琐,可以尝试下面的方法
import * as React from 'react'; const LoginForm = () => { // 将多个状态合并为对象 const [state, setState] = React.useState({ email: '', password: '', }); // 通过单个handler统一管理 const handleChange = (e) => { setState({ ...state, [e.target.id]: e.target.value, }); }; const handleSubmit = (e) => { e.preventDefault(); alert(state.email + ' ' + state.password); }; return ( <form onSubmit={handleSubmit}> <div> <label htmlFor="email">Email</label> <input id="email" type="text" value={state.email} onChange={handleChange} /> </div> <div> <label htmlFor="password">Password</label> <input id="password" type="password" value={state.password} onChange={handleChange} /> </div> <button type="submit">Submit</button> </form> ); }; export { LoginForm };
重置Form状态
由于每次用户输入后都需要数据重置回初始状态,可以使用以下方法来预设初始值,并重置Form内容,方便新用户的再次输入
import * as React from 'react'; const LoginForm = () => { // 初始 const [state, setState] = React.useState({ // 设置初始值 email: '123@456.com', password: '12345', }); const handleChange = (e) => { setState({ ...state, [e.target.id]: e.target.value, }); }; const handleSubmit = (e) => { e.preventDefault(); // 在这里重置状态 setState({ email: '', password: '', }); alert(state.email + ' ' + state.password); }; return ( <form onSubmit={handleSubmit}> <div> <label htmlFor="email">Email</label> <input id="email" type="text" value={state.email} onChange={handleChange} /> </div> <div> <label htmlFor="password">Password</label> <input id="password" type="password" value={state.password} onChange={handleChange} /> </div> <button type="submit">Submit</button> </form> ); }; export { LoginForm };
屏幕显示如下,submit后 Form内容会被重置
也可以考虑设置一个变量来统一管理初始值,方便对状态的查找和维护
import * as React from 'react'; const LoginForm = () => { // 定义初始值 const INITIAL_STATE = { email: '', password: '', }; const [state, setState] = React.useState(INITIAL_STATE); const handleChange = (e) => { setState({ ...state, [e.target.id]: e.target.value, }); }; const handleSubmit = (e) => { e.preventDefault(); // 重置初始值 setState(INITIAL_STATE); }; return ( <form onSubmit={handleSubmit}> <div> <label htmlFor="email">Email</label> <input id="email" type="text" value={state.email} onChange={handleChange} /> </div> <div> <label htmlFor="password">Password</label> <input id="password" type="password" value={state.password} onChange={handleChange} /> </div> <button type="submit">Submit</button> </form> ); }; export { LoginForm };
form验证
验证Form的输入是不可或缺的流程,可参考以下方案
import * as React from 'react'; const LoginForm = () => { const INITIAL_STATE = { email: '', password: '', }; // 设置Validation要求 const VALIDATION = { email: [ { isValid: (value) => !!value, message: 'Is required.', }, { isValid: (value) => /\S+@\S+\.\S+/.test(value), message: 'Needs to be an email.', }, ], password: [ { isValid: (value) => !!value, message: 'Is required.', }, ], }; // 获取ErrorsFields const getErrorState = (state) => Object.keys(state).reduce((acc, key) => { if (!VALIDATION[key]) return acc; const errorsPerField = VALIDATION[key].map((validation) => ({ isValid: validation.isValid(state[key]), message: validation.message, })).filter((errorPerField) => !errorPerField.isValid); return { ...acc, [key]: errorsPerField }; }, {}); const [state, setState] = React.useState(INITIAL_STATE); // 设置错误信息变量 const errorState = getErrorState(state); console.log(errorState); const handleChange = (e) => { setState({ ...state, [e.target.id]: e.target.value, }); }; const handleSubmit = (e) => { e.preventDefault(); // 获取错误反馈 const hasErrors = Object.values(errorFields).flat().length > 0; if (hasErrors) return; setState(INITIAL_STATE); }; return ( <form onSubmit={handleSubmit}> <div> <label htmlFor="email">Email</label> <input id="email" type="text" value={state.email} onChange={handleChange} /> {/* 显示email错误 */} {errorState.email?.length ? ( <span style={{ color: 'red' }}> {errorState.email[0].message} </span> ) : null} </div> <div> <label htmlFor="password">Password</label> <input id="password" type="password" value={state.password} onChange={handleChange} /> {/* 显示password错误 */} {errorState.password?.length ? ( <span style={{ color: 'red' }}> {errorState.password[0].message} </span> ) : null} </div> <button type="submit">Submit</button> </form> ); }; export { LoginForm };
效果显示如下
小结
到这里完成一个简易的React Login Form, 然而现实中React Form的问题还有很多, 随着学习的深入,会继续探索Form实用的复杂性,更多关于React特征Form数据管理的资料请关注易盾网络其它相关文章!