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节点控制。

相关推荐
崔庆才丨静觅3 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60614 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了4 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅4 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅4 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅5 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment5 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅5 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊5 小时前
jwt介绍
前端
爱敲代码的小鱼5 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax