当前位置:首页 > 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

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

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

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

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

react的refs如何取值

标签: reactrefs
分享给朋友:

相关文章

如何优化react

如何优化react

优化 React 性能的方法 使用 React.memo 或 PureComponent 对于函数组件,使用 React.memo 进行记忆化,避免不必要的重新渲染。类组件可以使用 PureCompo…

如何下载react

如何下载react

下载 React 的方法 通过 npm 或 yarn 安装 React 可以通过包管理器 npm 或 yarn 安装。确保已安装 Node.js(包含 npm),然后在项目目录中运行以下命令:…

react如何调试

react如何调试

调试 React 应用的方法 使用 React Developer Tools React Developer Tools 是 Chrome 和 Firefox 的浏览器扩展,可以检查组件树、状态和…

react 如何调试

react 如何调试

调试 React 应用的方法 使用 React Developer Tools 安装 Chrome 或 Firefox 的 React Developer Tools 扩展,可以检查组件树、状态和 p…

如何提高react

如何提高react

优化性能 使用React.memo对组件进行记忆化处理,避免不必要的重新渲染。对于类组件,可以使用PureComponent来达到类似效果。 利用useMemo缓存计算结果,避免重复计算。对于函数或…

react如何清理

react如何清理

清理 React 项目的方法 清理未使用的依赖项 运行 npm prune 或 yarn install --production 可以移除 node_modules 中未在 package.json…