react中refs的作用是什么?有几种用法?

在 React 中,ref 是用来获取组件或 DOM 元素的引用的一种方式。ref 可以在组件挂载后被访问,并且允许您从组件中访问底层的 DOM 元素或组件实例。

ref 有两种用法:字符串 ref 和回调函数 ref。

  1. 字符串 ref(string refs)是一种早期的使用 ref 的方式。它通过设置 ref 属性为一个字符串,将 ref 关联到一个 DOM 元素或组件实例上。然后可以通过 this.refs 获取这个 ref。

    javascript 复制代码
    class MyComponent extends React.Component {
      componentDidMount() {
        const input = this.refs.myInput;
        input.focus();
      }
    
      render() {
        return(
          <div>
            <input type="text" ref="myInput" />
          </div>
        );
      }
    }
  2. 回调函数 ref(callback refs)是一种现代而常用的使用 ref 的方式。它通过设置 ref 属性为一个回调函数,将 ref 关联到一个 DOM 元素或组件实例上。当组件挂载或卸载时,React 会调用这个回调函数,并将 DOM 元素或组件实例作为参数传递进去。

    javascript 复制代码
    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.inputRef = null;
      }
    
      componentDidMount() {
        this.inputRef.focus();
      }
    
      setInputRef = (ref) => {
        this.inputRef = ref;
      };
    
      render() {
        return (
          <div>
            <input type="text" ref={this.setInputRef} />
          </div>
        );
      }
    }

    需要注意的是,字符串 ref 在 React v16.3 之后被废弃了,建议使用回调函数 ref。此外,对于函数组件,可以使用 useRef Hook 来获取组件或 DOM 元素的引用

相关推荐
excel7 小时前
ES6 中函数的双重调用方式:fn() 与 fn\...``
前端
可乐爱宅着7 小时前
全栈框架next.js入手指南
前端·next.js
你的人类朋友9 小时前
什么是API签名?
前端·后端·安全
会豪11 小时前
Electron-Vite (一)快速构建桌面应用
前端
中微子11 小时前
React 执行阶段与渲染机制详解(基于 React 18+ 官方文档)
前端
唐某人丶11 小时前
教你如何用 JS 实现 Agent 系统(2)—— 开发 ReAct 版本的“深度搜索”
前端·人工智能·aigc
中微子11 小时前
深入剖析 useState产生的 setState的完整执行流程
前端
遂心_11 小时前
JavaScript 函数参数传递机制:一道经典面试题解析
前端·javascript
小徐_233311 小时前
uni-app vue3 也能使用 Echarts?Wot Starter 是这样做的!
前端·uni-app·echarts
RoyLin11 小时前
TypeScript设计模式:适配器模式
前端·后端·node.js