返回

函数组件和类组件创建Ref的方法

前端

函数组件和类组件创建 Ref 的方法

在 React 开发过程中,有时会遇到一些需要操控 DOM 的需求。这时,我们可以给组件挂载一个 ref 属性,然后就可以通过 ref 调用组件的方法或属性。接下来,我们就来看看函数组件和类组件是怎样创建 Ref 的。

函数组件创建 Ref

在函数组件中,可以使用 useRef 钩子来创建 Ref。useRef 钩子返回一个可变的 ref 对象。该对象有一个 .current 属性,该属性指向当前组件实例。

import React, { useRef } from "react";

const MyFunctionComponent = () => {
  const ref = useRef(null);

  // 在这里,我们可以在组件中使用 ref
  console.log(ref.current);

  return <div ref={ref}>Hello, world!</div>;
};

export default MyFunctionComponent;

类组件创建 Ref

在类组件中,可以使用 createRef() 方法来创建 Ref。createRef() 方法返回一个可变的 ref 对象。该对象有一个 .current 属性,该属性指向当前组件实例。

import React, { Component } from "react";

class MyClassComponent extends Component {
  constructor(props) {
    super(props);

    // 在这里,我们可以在构造函数中创建 ref
    this.ref = React.createRef();
  }

  // 在这里,我们可以在组件中使用 ref
  componentDidMount() {
    console.log(this.ref.current);
  }

  render() {
    return <div ref={this.ref}>Hello, world!</div>;
  }
}

export default MyClassComponent;

函数组件和类组件创建 Ref 的区别

函数组件和类组件创建 Ref 的区别在于,函数组件可以使用 useRef 钩子来创建 Ref,而类组件可以使用 createRef() 方法来创建 Ref。此外,函数组件的 Ref 是一个对象,而类组件的 Ref 是一个函数。

总结

函数组件和类组件都可以创建 Ref。函数组件使用 useRef 钩子来创建 Ref,而类组件使用 createRef() 方法来创建 Ref。函数组件的 Ref 是一个对象,而类组件的 Ref 是一个函数。