react实现表单
React 表单实现方法
React 提供了多种方式实现表单功能,包括受控组件、非受控组件以及结合第三方库如 Formik 或 React Hook Form。以下是常见实现方法:
受控组件方式
受控组件将表单数据存储在组件状态中,通过事件处理器同步更新。这是 React 推荐的标准做法。
import { useState } from 'react';
function ControlledForm() {
const [formData, setFormData] = useState({
username: '',
password: ''
});
const handleChange = (e) => {
const { name, value } = e.target;
setFormData(prev => ({
...prev,
[name]: value
}));
};
const handleSubmit = (e) => {
e.preventDefault();
console.log('Submitted:', formData);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="username"
value={formData.username}
onChange={handleChange}
/>
<input
type="password"
name="password"
value={formData.password}
onChange={handleChange}
/>
<button type="submit">Submit</button>
</form>
);
}
非受控组件方式
非受控组件通过 ref 直接访问 DOM 元素获取表单值,适合简单表单或需要集成非 React 代码时使用。
import { useRef } from 'react';
function UncontrolledForm() {
const usernameRef = useRef();
const passwordRef = useRef();
const handleSubmit = (e) => {
e.preventDefault();
console.log('Submitted:', {
username: usernameRef.current.value,
password: passwordRef.current.value
});
};
return (
<form onSubmit={handleSubmit}>
<input type="text" ref={usernameRef} />
<input type="password" ref={passwordRef} />
<button type="submit">Submit</button>
</form>
);
}
使用 Formik 库
Formik 提供了完整的表单解决方案,包括验证、错误处理和表单状态管理。
import { Formik, Field, Form } from 'formik';
function FormikForm() {
return (
<Formik
initialValues={{ username: '', password: '' }}
onSubmit={(values) => {
console.log('Submitted:', values);
}}
>
<Form>
<Field name="username" type="text" />
<Field name="password" type="password" />
<button type="submit">Submit</button>
</Form>
</Formik>
);
}
使用 React Hook Form
React Hook Form 是轻量级表单库,性能优化好且 API 简洁。
import { useForm } from 'react-hook-form';
function HookForm() {
const { register, handleSubmit } = useForm();
const onSubmit = (data) => {
console.log('Submitted:', data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} />
<input {...register('password')} type="password" />
<button type="submit">Submit</button>
</form>
);
}
表单验证实现
表单验证是重要环节,以下是常见验证方式:
基础验证
在受控组件中直接添加验证逻辑:
const [errors, setErrors] = useState({});
const validate = () => {
const newErrors = {};
if (!formData.username) newErrors.username = 'Required';
if (formData.password.length < 6) newErrors.password = 'Too short';
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const handleSubmit = (e) => {
e.preventDefault();
if (validate()) {
console.log('Valid submission:', formData);
}
};
Yup 验证方案
结合 Yup 库实现声明式验证规则:
import * as Yup from 'yup';
const schema = Yup.object().shape({
username: Yup.string().required('Required'),
password: Yup.string().min(6, 'Too short')
});
// 在 Formik 中使用
<Formik
validationSchema={schema}
// ...其他属性
>
{({ errors }) => (
<Form>
<Field name="username" />
{errors.username && <div>{errors.username}</div>}
{/* 其他字段 */}
</Form>
)}
</Formik>
复杂表单处理
对于动态表单或复杂结构,可采用以下模式:
// 动态字段数组
const [fields, setFields] = useState([{ name: '', value: '' }]);
const addField = () => {
setFields([...fields, { name: '', value: '' }]);
};
const handleFieldChange = (index, e) => {
const newFields = [...fields];
newFields[index][e.target.name] = e.target.value;
setFields(newFields);
};
性能优化技巧
大型表单可通过以下方式优化性能:
- 对非关键字段使用非受控组件
- 对复杂表单使用 React.memo 优化子组件
- 避免在顶层组件管理所有表单状态
- 使用防抖处理频繁的状态更新
const DebouncedInput = React.memo(({ value, onChange }) => {
const [localValue, setLocalValue] = useState(value);
useEffect(() => {
const timer = setTimeout(() => onChange(localValue), 500);
return () => clearTimeout(timer);
}, [localValue, onChange]);
return (
<input
value={localValue}
onChange={(e) => setLocalValue(e.target.value)}
/>
);
});






