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

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

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

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

  1. 字符串 ref(string refs)是一种早期的使用 ref 的方式。它通过设置 ref 属性为一个字符串,将 ref 关联到一个 DOM 元素或组件实例上。然后可以通过 this.refs 获取这个 ref。
class MyComponent extends React.Component {
  componentDidMount() {
    const input = this.refs.myInput;
    input.focus();
  }
  render() {
    return(
      <div>
        <input type="text" ref="myInput" />
      </div>
    );
  }
}
  1. 回调函数 ref(callback refs)是一种现代而常用的使用 ref 的方式。它通过设置 ref 属性为一个回调函数,将 ref 关联到一个 DOM 元素或组件实例上。当组件挂载或卸载时,React 会调用这个回调函数,并将 DOM 元素或组件实例作为参数传递进去。
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>
    );
  }
}
  1. 需要注意的是,字符串 ref 在 React v16.3 之后被废弃了,建议使用回调函数 ref。此外,对于函数组件,可以使用 useRef Hook 来获取组件或 DOM 元素的引用
相关文章
|
7月前
react-withRouter 用法
react-withRouter 用法
92 0
|
1月前
|
前端开发 UED
React 防抖与节流用法
React 防抖与节流用法
51 0
|
1月前
|
JavaScript 前端开发 Java
React 中的 ref 和 refs:解锁更多可能性(下)
React 中的 ref 和 refs:解锁更多可能性(下)
React 中的 ref 和 refs:解锁更多可能性(下)
|
1月前
|
JavaScript 前端开发 测试技术
React 中的 ref 和 refs:解锁更多可能性(上)
React 中的 ref 和 refs:解锁更多可能性(上)
React 中的 ref 和 refs:解锁更多可能性(上)
|
1月前
|
前端开发 JavaScript API
React 之 Refs 的使用和 forwardRef 的源码解读
React 之 Refs 的使用和 forwardRef 的源码解读
49 1
|
1月前
|
存储 前端开发 JavaScript
[React] useRef用法和特性
[React] useRef用法和特性
|
1月前
|
前端开发 JavaScript
React 中 refs 的作用是什么
React 中 refs 的作用是什么
|
9月前
|
前端开发 JavaScript
React Hooks 用法详解3
React Hooks 用法详解
|
9月前
|
前端开发 JavaScript API
React Hooks 用法详解2
React Hooks 用法详解
|
9月前
|
缓存 前端开发 JavaScript
React Hooks 用法详解1
React Hooks 用法详解