PHP前端开发

React 设计模式~容器组件/不受控制的受控组件~

百变鹏仔 3天前 #JavaScript
文章标签 组件

这种模式意味着 react 不控制表单数据,dom 保存表单状态。

访问 dom 时,必须使用 useref 钩子设置 ref 属性。

・src/components/uncontrol-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 (    
);};

此模式意味着 react 使用 usestate 钩子控制表单数据。

我们可以完全控制输入值并实时更新。

import React, { useEffect, useState } from "react";export const ControlledForm = () =&gt; {  const [errorMessage, setErrorMessage] = useState("");  const [name, setName] = useState("");  const [age, setAge] = useState();  useEffect(() =&gt; {    if (name.length       {errorMessage&amp;&amp; <p>{errorMessage}</p>}      <input type="text" name="name" placeholder="Name" value="{name}" onchange="{(e)"> setName(e.target.value)}      /&gt;      <input type="number" name="age" placeholder="Age" value="{age}" onchange="{(e)"> setAge(e.target.value)}      /&gt;      <button>Submit</button>      );};