首頁  >  文章  >  web前端  >  中級:在 React 中管理表單

中級:在 React 中管理表單

王林
王林原創
2024-07-18 07:28:19745瀏覽

Mid level: Managing Forms in React

表單對於在 Web 應用程式中收集使用者輸入至關重要。在 React 中管理表單可能會變得複雜,尤其是在處理驗證、多步驟流程和文件上傳時。本指南深入探討了管理表單的狀態、使用參考、實作驗證以及處理複雜表單。

受控組件

受控元件是由元件狀態處理表單資料的元件。這種方法確保 React 完全控製表單輸入,從而實現可預測和可管理的表單行為。

使用狀態處理表單數據

要建立受控元件,請設定表單資料的狀態並根據使用者輸入更新狀態。

範例:

import React, { useState } from 'react';

const ControlledForm = () => {
  const [formData, setFormData] = useState({
    name: '',
    email: ''
  });

  const handleChange = (event) => {
    const { name, value } = event.target;
    setFormData((prevData) => ({
      ...prevData,
      [name]: value
    }));
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`Name: ${formData.name}, Email: ${formData.email}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input
          type="text"
          name="name"
          value={formData.name}
          onChange={handleChange}
        />
      </label>
      <br />
      <label>
        Email:
        <input
          type="email"
          name="email"
          value={formData.email}
          onChange={handleChange}
        />
      </label>
      <br />
      <button type="submit">Submit</button>
    </form>
  );
};

export default ControlledForm;

在此範例中,useState 管理表單數據,而每當使用者在輸入欄位中鍵入內容時,handleChange 函數就會更新狀態。

不受控制的組件

不受控制的元件依賴 DOM 來處理表單資料。您可以使用 refs 直接從 DOM 元素存取表單資料。

使用 Refs 存取表單數據

要建立不受控制的元件,請使用 useRef 掛鉤為表單元素建立參考。

範例:

import React, { useRef } from 'react';

const UncontrolledForm = () => {
  const nameRef = useRef(null);
  const emailRef = useRef(null);

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`Name: ${nameRef.current.value}, Email: ${emailRef.current.value}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" ref={nameRef} />
      </label>
      <br />
      <label>
        Email:
        <input type="email" ref={emailRef} />
      </label>
      <br />
      <button type="submit">Submit</button>
    </form>
  );
};

export default UncontrolledForm;

在此範例中,nameRef 和 emailRef 引用用於在提交表單時直接從 DOM 元素存取輸入值。

表單驗證

表單驗證對於確保使用者輸入在提交之前滿足所需標準至關重要。

基本驗證技術

您可以透過檢查表單提交處理程序中的輸入值來新增基本驗證。

範例:

import React, { useState } from 'react';

const BasicValidationForm = () => {
  const [formData, setFormData] = useState({
    name: '',
    email: ''
  });
  const [errors, setErrors] = useState({});

  const handleChange = (event) => {
    const { name, value } = event.target;
    setFormData((prevData) => ({
      ...prevData,
      [name]: value
    }));
  };

  const validate = () => {
    const newErrors = {};
    if (!formData.name) newErrors.name = 'Name is required';
    if (!formData.email) newErrors.email = 'Email is required';
    return newErrors;
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    const newErrors = validate();
    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
    } else {
      alert(`Name: ${formData.name}, Email: ${formData.email}`);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input
          type="text"
          name="name"
          value={formData.name}
          onChange={handleChange}
        />
        {errors.name && <span>{errors.name}</span>}
      </label>
      <br />
      <label>
        Email:
        <input
          type="email"
          name="email"
          value={formData.email}
          onChange={handleChange}
        />
        {errors.email && <span>{errors.email}</span>}
      </label>
      <br />
      <button type="submit">Submit</button>
    </form>
  );
};

export default BasicValidationForm;

在此範例中,驗證函數檢查名稱和電子郵件欄位是否為空並相應地設定錯誤訊息。

用於表單驗證的第三方函式庫

使用 Formik 和 Yup 等第三方函式庫可以簡化表單驗證。

Formik 和 Yup 的範例:

import React from 'react';
import { Formik, Field, Form, ErrorMessage } from 'formik';
import * as Yup from 'yup';

const SignupSchema = Yup.object().shape({
  name: Yup.string().required('Name is required'),
  email: Yup.string().email('Invalid email').required('Email is required'),
});

const FormikForm = () => (
  <div>
    <h1>Signup Form</h1>
    <Formik
      initialValues={{ name: '', email: '' }}
      validationSchema={SignupSchema}
      onSubmit={(values) => {
        alert(JSON.stringify(values, null, 2));
      }}
    >
      {({ errors, touched }) => (
        <Form>
          <label>
            Name:
            <Field name="name" />
            <ErrorMessage name="name" component="div" />
          </label>
          <br />
          <label>
            Email:
            <Field name="email" type="email" />
            <ErrorMessage name="email" component="div" />
          </label>
          <br />
          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
  </div>
);

export default FormikForm;

在此範例中,Formik 和 Yup 用於處理表單狀態和驗證。 Formik 提供了一種靈活且簡單的方式來管理表單,而 Yup 則有助於定義驗證模式。

複雜表單管理

管理多步驟表單

管理多步驟表單涉及處理表單狀態和步驟之間的導航。

範例:

import React, { useState } from 'react';

const MultiStepForm = () => {
  const [step, setStep] = useState(1);
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    address: '',
  });

  const nextStep = () => setStep(step + 1);
  const prevStep = () => setStep(step - 1);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prevData) => ({
      ...prevData,
      [name]: value
    }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    alert(JSON.stringify(formData, null, 2));
  };

  switch (step) {
    case 1:
      return (
        <form>
          <h2>Step 1</h2>
          <label>
            Name:
            <input
              type="text"
              name="name"
              value={formData.name}
              onChange={handleChange}
            />
          </label>
          <button type="button" onClick={nextStep}>
            Next
          </button>
        </form>
      );
    case 2:
      return (
        <form>
          <h2>Step 2</h2>
          <label>
            Email:
            <input
              type="email"
              name="email"
              value={formData.email}
              onChange={handleChange}
            />
          </label>
          <button type="button" onClick={prevStep}>
            Back
          </button>
          <button type="button" onClick={nextStep}>
            Next
          </button>
        </form>
      );
    case 3:
      return (
        <form onSubmit={handleSubmit}>
          <h2>Step 3</h2>
          <label>
            Address:
            <input
              type="text"
              name="address"
              value={formData.address}
              onChange={handleChange}
            />
          </label>
          <button type="button" onClick={prevStep}>
            Back
          </button>
          <button type="submit">Submit</button>
        </form>
      );
    default:
      return null;
  }
};

export default MultiStepForm;

在此範例中,表單狀態透過多個步驟進行管理。 nextStep 和 prevStep 函數處理步驟之間的導航。

處理表單中的檔案上傳

處理文件上傳涉及使用文件輸入元素並在元件狀態下管理上傳的文件。

範例


import React, { useState } from 'react';

const FileUploadForm = () => {
  const [file, setFile] = useState(null);

  const handleFileChange = (e) => {
    setFile(e.target.files[0]);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (file) {
      alert(`File name: ${file.name}`);
    } else {
      alert('No file selected');
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Upload file:
        <input type="file" onChange={handleFileChange} />
      </label>
      <br />
      <button type="submit">Submit</button>
    </form>
  );
};

export default FileUploadForm;

在此範例中,handleFileChange 函數使用所選檔案更新狀態,handleSubmit 函數處理表單提交。

結論

在 React 中管理表單涉及了解受控和非受控元件、實作表單驗證以及處理複雜表單。透過掌握這些概念,您可以在 React 應用程式中建立健全且使用者友好的表單。作為中級開發人員,在這些領域打下堅實的基礎將增強您開發更複雜、更可靠的表單的能力,使您成為 React 生態系統中更有效、更有效率的開發人員。

以上是中級:在 React 中管理表單的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn