首页  >  文章  >  web前端  >  React Design Patterns~Container Componets / Uncontrolled Controlled Component~

React Design Patterns~Container Componets / Uncontrolled Controlled Component~

Barbara Streisand
Barbara Streisand原创
2024-09-24 06:15:02672浏览

React Design Patterns~Container Componets / Uncontrolled Controlled Component~

  • Uncontrolled Component

This pattern means that React doesn't control the form data, and the DOM holds the form state.

When you access the DOM, you must set the ref attribute using the useRef hook.

・src/components/uncontrolled-form.jsx

import React from "react";

export const UncontrolledForm = () => {
  const nameInputRef = React.createRef();
  const ageInputRef = React.createRef();

  console.log("renedering");

  const SubmitForm = (e) => {
    console.log(nameInputRef.current.value);
    console.log(ageInputRef.current.value);

    e.preventDefault();
  };

  return (
    <form onSubmit={SubmitForm}>
      <input name="name" type="text" placeholder="Name" ref={nameInputRef} />
      <input name="age" type="number" placeholder="Age" ref={ageInputRef} />
      <input type="submit" value="Submit" />
    </form>
  );
};
  • Controlled Component

This pattern means that React controls the form data using the useState hook.

We can fully control the input value and update it in real time.

import React, { useEffect, useState } from "react";

export const ControlledForm = () => {
  const [errorMessage, setErrorMessage] = useState("");
  const [name, setName] = useState("");
  const [age, setAge] = useState();

  useEffect(() => {
    if (name.length < 1) {
      setErrorMessage("name can not be empty");
    } else {
      setErrorMessage("");
    }
  }, [name]);

  return (
    <form>
      {errorMessage&& <p>{errorMessage}</p>}
      <input
        type="text"
        name="name"
        placeholder="Name"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <input
        type="number"
        name="age"
        placeholder="Age"
        value={age}
        onChange={(e) => setAge(e.target.value)}
      />
      <button>Submit</button>
    </form>
  );
};

以上是React Design Patterns~Container Componets / Uncontrolled Controlled Component~的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn