React.forwardRef 会创建一个React组件,这个组件能够将其接受的 ref 属性转发到其组件树下的另一个组件中。这种技术并不常见,但在以下两种场景中特别有用:

  • 转发 refs 到 DOM 组件
  • 在高阶组件中转发 refs

本文重点介绍下React forwardRef 用法。

用法

forwardRef:允许你的组件使用 ref 将一个 DOM 节点暴露给父组件。

import { forwardRef } from 'react';
const MyInput = forwardRef((props, ref) => {
  // ...
});

案例分析:ref 属性是 React 的特殊属性,不能直接使用。

import {useRef} from 'react'
function InputCom({ref}) {
  return (
    <input type='text' ref={ref} />
  )
}
function App() {
  const inpRef = useRef(null)
  const focus = () => {
    inpRef.current?.focus()
  }
  return (
    <>
      <InputCom ref={inpRef} />
    </>
  )
}

上面就会弹出报错信息:

Warning: InputCom: `ref` is not a prop. Trying to access it will result in `undefined` being returned. 
If you need to access the same value Within the child component, you should pass it as a company's prop.
// 警告:InputCom: 'ref不是一个prop。试图访问它将导致返回undefine。如果你需要在子组件中访问相同的值,你应该把它作为公司的prop传递。

如果想传递 ref,这时候就要借助 forwardRef 函数

import { forwardRef, useRef } from "react";
const InputCom = forwardRef((props, ref) => {
  return <input type="text" ref={ref} />;
});
export default function ProRef() {
  const inpRef = useRef(null);
  const focus = () => {
    inpRef.current?.focus();
  };
  return (
    <>
      <InputCom ref={inpRef} />
      <button onClick={focus}>focus</button>
    </>
  );
}