首页 > web前端 > js教程 > 正文

React Design Patterns~Container Componets / Uncontrolled Controlled Component~

Barbara Streisand
发布: 2024-09-24 06:15:02
原创
676 人浏览过

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中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板