React获取form表单值的N种方式

Ref模式(非受控模式)

非钩子模式
javascript 复制代码
1.createRef()方式
js:
userNameEl=createRef()
<input type="text" name="userName" ref={this.userNameEl} />
获取值的方式:
this.userNameEl.current.value

2.refs(废弃)
js:
const { userName } = this.refs;

<input type="text" name="userName" ref="userName" />

3.回调函数方式(不推荐)
js:
this.userNameRef.value
<input type="text" name="userName" ref={(el) => (this.userNameRef = el)} />
钩子函数模式
javascript 复制代码
import React, { useRef, useEffect } from 'react';
function MyComponent() {
  const myRef = useRef();
  useEffect(() => {
    myRef.current.focus();
  }, []);
  return <input ref={myRef} />;
}

非ref模式(受控模式)

非钩子模式
javascript 复制代码
import { Component } from "react";
export default class TestValue extends Component {
  state = {
    userName: null,
  };
  inputChange = (e) => {
    this.setState({ userName: e.target.value });
  };
  getInputValue = () => {
    console.log(this.state.userName);
  };
  render() {
    return (
      <div>
        <input type="text" name="userName" onChange={this.inputChange} />
        <button onClick={this.getInputValue}>TestValue</button>
      </div>
    );
  }
}
钩子模式
javascript 复制代码
import { useState } from "react";
export default function TestValue() {
  //函数式组件使用
  const [userName, setUserName] = useState(null);

  function inputChange(e) {
    setUserName(e.target.value);
  }
  function getInputValue() {
    console.log(userName);
  }
  return (
    <div>
      <input type="text" name="userName" onChange={inputChange} />
      <button onClick={getInputValue}>TestValue</button>
    </div>
  );
}

总结

ref模式和非ref模式的区别

ref模式是在类组件或使用Hooks的函数组件中创建并使用ref的方式,可以用来访问和控制DOM节点或其他组件实例。非ref模式主要是指无状态组件,它们不支持ref。

受控组件和非受控组件的区别

React受控组件和非受控组件之间的最大区别是组件的值是由React状态控制还是由DOM节点控制。

相关推荐
小屁孩大帅-杨一凡8 分钟前
一个简单点的js的h5页面实现地铁快跑的小游戏
开发语言·前端·javascript·css·html
读心悦13 分钟前
CSS 布局系统深度解析:从传统到现代的布局方案
前端·css
椒盐螺丝钉18 分钟前
CSS盒子模型:Padding与Margin的适用场景与注意事项
前端·css
萧鼎1 小时前
构建全栈 Web 应用的新选择:NextPy 技术详解与实战指南
前端
purpleseashell_Lili1 小时前
配置别名路径 @
javascript·react
这个一个非常哈2 小时前
VUE篇之自定义组件使用v-model
前端·javascript·vue.js
purpleseashell_Lili2 小时前
react 基本写法
java·服务器·前端
哎哟喂_!2 小时前
Node.js 循环依赖问题详解:原理、案例与解决方案
前端·chrome·node.js
热爱前端的小君同学2 小时前
长按拖拽移动的vue3组件
前端·javascript·vue.js
Coding的叶子2 小时前
Node.js 安装 + React Flow 快速入门:环境安装与项目搭建
react.js·node.js·react flow·fgai·react agent