使用 React.forwardRef 的示例

20 min read

在这个示例中,我们将创建一个简单的自定义按钮组件,它能够接受外部传递的引用(ref)。

import React from 'react';

// 自定义按钮组件
const CustomButton = React.forwardRef((props, ref) => {
  // 使用外部传递的 ref
  return <button ref={ref} {...props}>点击我</button>;
});

// 设置显示名称,有助于调试
CustomButton.displayName = 'CustomButton';

// 在应用中使用这个组件
const App = () => {
  // 创建一个 ref 来引用按钮
  const buttonRef = React.createRef();

  // 模拟点击按钮
  const handleClick = () => {
    if (buttonRef.current) {
      buttonRef.current.click();
    }
  };

  return (
    <div>
      <CustomButton ref={buttonRef}>我是一个按钮</CustomButton>
      <button onClick={handleClick}>模拟点击上面的按钮</button>
    </div>
  );
};

export default App;

在这个示例中:

  1. 创建自定义按钮组件:

    • 使用 React.forwardRef 创建 CustomButton 组件。
    • 组件接受一个 ref 作为参数,这个 ref 可以是由父组件传递的。
    • ref 应用到 button 元素上。
  2. 设置 displayName:

    • CustomButton 设置 displayName,这在调试时尤其有用。
  3. 使用组件:

    • App 组件中,创建一个 buttonRef 引用并将其传递给 CustomButton
    • 创建一个模拟按钮来演示如何使用这个引用来触发按钮的点击事件。

这个示例展示了如何在自定义组件中使用 forwardRef 来转发引用,并在父组件中如何操作这个引用。这种做法在需要直接访问 DOM 元素或执行 DOM 操作(例如聚焦、动画等)的时候非常有用。