React 中的 ref 使用
trycoding.fun
React

React 中的 ref 使用

理解 ref 的作用和在不同场景下的使用方式

问题

React 中的 ref 有什么用?

解答

ref 用于获取组件实例或 DOM 节点的引用。当组件被挂载后,ref 会指向对应的实例或节点。

在原生 DOM 组件中使用

ref 可以直接获取 DOM 节点:

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

  focusInput = () => {
    this.inputRef.current.focus();
  }

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

在 React 类组件中使用

ref 获取的是组件实例,可以调用实例方法:

class Child extends React.Component {
  sayHello() {
    console.log('Hello');
  }

  render() {
    return <div>Child Component</div>;
  }
}

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

  handleClick = () => {
    this.childRef.current.sayHello();
  }

  render() {
    return <Child ref={this.childRef} />;
  }
}

在函数组件中使用

函数组件本身不能使用 ref(因为没有实例),但可以使用 useRef Hook:

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

  const focusInput = () => {
    inputRef.current.focus();
  };

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

如果需要在父组件中获取子函数组件的 ref,需要配合 forwardRef 使用:

const Child = React.forwardRef((props, ref) => {
  return <input ref={ref} />;
});

function Parent() {
  const inputRef = useRef(null);
  return <Child ref={inputRef} />;
}

关键点

  • ref 在原生 DOM 组件上获取的是 DOM 节点,在类组件上获取的是组件实例
  • 函数组件没有实例,不能直接使用 ref,需要通过 useRef Hook 或 forwardRef 实现
  • 避免使用 ReactDOM.findDOMNode 来访问组件的真实 DOM,这是过时的做法
  • ref 的回调函数会在组件挂载后立即执行