当前位置:首页 > React

react实现表单

2026-01-26 13:34:16React

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实现表单

  • 对非关键字段使用非受控组件
  • 对复杂表单使用 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)}
    />
  );
});

标签: 表单react
分享给朋友:

相关文章

vue新增表单实现

vue新增表单实现

Vue 表单实现方法 使用 Vue 实现新增表单功能可以通过多种方式完成,以下是一些常见的方法和步骤: 使用 v-model 双向绑定 在 Vue 中,v-model 指令可以实现表单输入和应用状态…

如何react页面

如何react页面

创建 React 页面 使用 create-react-app 快速初始化项目: npx create-react-app my-app cd my-app npm start 基础页面结构 在 s…

react如何收录

react如何收录

React 收录方法 React 的收录主要涉及搜索引擎优化(SEO)和预渲染技术。由于 React 是单页应用(SPA),默认情况下内容由 JavaScript 动态生成,可能导致搜索引擎爬虫难以收…

react如何开发

react如何开发

React 开发基础步骤 安装 Node.js 和 npm/yarn 确保系统已安装 Node.js(包含 npm)或 Yarn。React 项目依赖这些工具管理包和运行脚本。官方推荐使用 Node.…

react如何发布

react如何发布

发布React应用的步骤 构建生产版本 使用以下命令生成优化后的生产版本代码,代码会被压缩并移除开发环境中的调试工具: npm run build 构建完成后会生成build文件夹,包含所有静态资源…

react 如何获取dom

react 如何获取dom

获取 DOM 的方法 在 React 中,可以通过 useRef 或 createRef 来获取 DOM 节点。useRef 是函数组件中常用的方法,而 createRef 通常用于类组件。 使用…