当前位置:首页 > React

react的refs如何取值

2026-01-24 08:23:38React

获取 React Refs 的值

在 React 中,refs 用于直接访问 DOM 元素或 React 组件实例。根据 React 版本和使用方式的不同,获取 refs 值的方法也有所区别。

函数组件中使用 useRef

import React, { useRef } from 'react';

function MyComponent() {
  const inputRef = useRef(null);

  const handleClick = () => {
    console.log(inputRef.current.value); // 获取输入框的值
  };

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={handleClick}>Get Value</button>
    </div>
  );
}

类组件中使用 createRef

import React, { Component } from 'react';

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }

  handleClick = () => {
    console.log(this.inputRef.current.value); // 获取输入框的值
  };

  render() {
    return (
      <div>
        <input ref={this.inputRef} type="text" />
        <button onClick={this.handleClick}>Get Value</button>
      </div>
    );
  }
}

回调 Refs(适用于旧版 React)

class MyComponent extends Component {
  handleClick = () => {
    console.log(this.inputRef.value); // 获取输入框的值
  };

  render() {
    return (
      <div>
        <input ref={el => (this.inputRef = el)} type="text" />
        <button onClick={this.handleClick}>Get Value</button>
      </div>
    );
  }
}

访问自定义组件的 Refs

如果 ref 被附加到自定义类组件,ref.current 将指向该组件的实例,可以调用其方法或访问其状态:

class CustomInput extends Component {
  focus = () => {
    this.inputRef.focus();
  };

  render() {
    return <input ref={el => (this.inputRef = el)} />;
  }
}

class Parent extends Component {
  componentRef = React.createRef();

  componentDidMount() {
    this.componentRef.current.focus(); // 调用子组件方法
  }

  render() {
    return <CustomInput ref={this.componentRef} />;
  }
}

注意事项

  • 函数组件默认不支持 ref,除非使用 forwardRef 转发。
  • 避免过度使用 refs,优先考虑 React 的数据流(props 和 state)。
  • ref.current 在组件挂载前为 null,需在 useEffectcomponentDidMount 中访问。

转发 Refs(forwardRef

若需在函数组件中暴露内部 DOM 节点的 ref

react的refs如何取值

const FancyInput = React.forwardRef((props, ref) => (
  <input ref={ref} className="fancy" />
));

function Parent() {
  const inputRef = useRef();

  useEffect(() => {
    inputRef.current.focus();
  }, []);

  return <FancyInput ref={inputRef} />;
}

标签: reactrefs
分享给朋友:

相关文章

react如何销毁

react如何销毁

React 组件销毁的机制 在 React 中,组件的销毁通常由 React 的生命周期管理。当组件从 DOM 中移除时,React 会自动触发销毁相关的生命周期方法。以下是关键点: 组件的销毁通常…

react如何读

react如何读

React 的发音 React 的发音为 /riˈækt/(音标),读作“瑞-艾克特”。其中: “Re” 发音类似英文单词 “read” 的开头部分。 “act” 发音与英文单词 “act” 一致。…

react 如何启动

react 如何启动

创建 React 项目 使用官方工具 create-react-app 快速初始化项目,需提前安装 Node.js(版本 ≥ 14.0.0)和 npm/yarn: npx create-react-…

如何构建react

如何构建react

构建 React 项目的步骤 安装 Node.js 和 npm 确保系统已安装 Node.js(包含 npm)。可通过命令行验证: node -v npm -v 使用 Create React Ap…

react如何扩展

react如何扩展

扩展 React 项目的常用方法 使用高阶组件(HOC) 高阶组件是一种复用组件逻辑的方式。通过包裹组件并注入额外属性或逻辑,可以实现功能扩展。例如,一个日志记录的高阶组件: function…

react如何引入

react如何引入

引入React的方法 React可以通过多种方式引入项目,具体取决于项目需求和开发环境。以下是常见的几种方法: 通过CDN引入 在HTML文件中直接通过CDN链接引入React和ReactDOM:…