TypeScript在React组件中应用备忘录(一)

前言

在React中,forwardRefuseImperativeHandle钩子常被用于函数组件,以暴露组件内部的方法给父组件。通过明确地定义和使用类型,我们可以提高组件间的交互质量,确保类型安全,并利用自动补全等IDE特性。以下借用FancyButton组件暴露focus方法的实现过程来介绍是如何进行类型定义的。

定义组件Props和Ref接口

首先,定义组件的props和ref接口,这有助于在组件外部通过ref对象调用组件内部的方法时获得类型检查和自动补全的好处。

tsx 复制代码
import React, { useImperativeHandle, createRef } from 'react';

export interface FancyButtonRef {
  focus: () => void;
}

interface FancyButtonProps {
  label: string;
  onClick?: () => void;
}

实现FancyButton组件

FancyButton组件中,我们使用React.forwardRefuseImperativeHandle来暴露focus方法。

tsx 复制代码
import React, { useImperativeHandle, createRef } from 'react';

export interface FancyButtonRef {
  focus: () => void;
}

interface FancyButtonProps {
  label: string;
  onClick?: () => void;
}

const FancyButton = React.forwardRef<FancyButtonRef, FancyButtonProps>(
  (props, ref) => {
    const { label, onClick } = props;
    const buttonRef = createRef<HTMLButtonElement>();
    
    useImperativeHandle(ref, () => ({
      focus: () => {
        buttonRef.current?.focus();
      },
    }));

    return (
      <button ref={buttonRef} onClick={onClick}>
        {label}
      </button>
    );
  }
);

export default FancyButton;

在父组件中使用FancyButton

父组件通过ref访问FancyButtonfocus方法,在以下代码中展示了如何在实际场景中使用这种方法。

tsx 复制代码
import { useRef } from 'react';
import FancyButton from './FancyButton';
import type { FancyButtonRef } from './FancyButton';

const ParentComponent: FC = () => {
  const fancyButtonRef = useRef<FancyButtonRef>(null);

  const onButtonClick = () => {
    fancyButtonRef.current?.focus();
  };

  return (
    <div>
      <FancyButton ref={fancyButtonRef} label="点击我" />
      <button onClick={onButtonClick}>使旁边这个按钮聚焦</button>
    </div>
  );
};

export default ParentComponent;

FancyButton组件的实现代码中,将FancyButtonRefFancyButtonProps作为forwardRef的泛型参数引入,这种做法会导致在父组件中通过ref对象调用FancyButton内部方法时,提供了类型检查和自动补全功能,从而增强了代码的健壮性和开发效率。

forwardRef包裹组件的子组件使用useImperativeHandle

tsx 复制代码
import React, { useImperativeHandle, forwardRef, createRef } from 'react';

interface FancyButtonProps {
  label: string;
  onClick?: () => void;
}

export interface FancyButtonRef {
  focus: () => void;
}

const InnierFancyButton: React.FC<any> = ({ ref, label, onClick }) => {
  const buttonRef = createRef<HTMLButtonElement>();

  useImperativeHandle(ref, () => ({
    focus: () => {
      buttonRef.current?.focus();
    },
  }));

  return (
    <button ref={buttonRef} onClick={onClick}>
      {label}
    </button>
  );
};

const FancyButton = forwardRef<FancyButtonRef, FancyButtonProps>(
  (props, ref) => {
    return (
      <InnierFancyButton {...props} ref={ref} />
    );
  }
);

export default FancyButton;

在实际开发中,并不会在forwardRef包裹组件中直接使用useImperativeHandle,也许会在组件的子组件中使用useImperativeHandle

比如在 InnierFancyButton 组件中使用 useImperativeHandle ,那么InnierFancyButton子组件的props类型如何定义?

这个很好定义,使用 extends 继承 FancyButtonProps 类型,再使用React.ForwardedRef<FancyButtonRef> 定义 ref 的类型。

diff 复制代码
import React, { useImperativeHandle, forwardRef, createRef } from 'react';

interface FancyButtonProps {
  label: string;
  onClick?: () => void;
}

export interface FancyButtonRef {
  focus: () => void;
}

+ interface InnierFancyButtonProps extends FancyButtonProps {
+   ref: React.ForwardedRef<FancyButtonRef>
+ }

- const InnierFancyButton: React.FC<any> = ({ ref, label, onClick }) => {
+ const InnierFancyButton: React.FC<InnierFancyButtonProps> = ({ ref, label, onClick }) => {
  const buttonRef = createRef<HTMLButtonElement>();

  useImperativeHandle(ref, () => ({
    focus: () => {
      buttonRef.current?.focus();
    },
  }));

  return (
    <button ref={buttonRef} onClick={onClick}>
      {label}
    </button>
  );
};

const FancyButton = forwardRef<FancyButtonRef, FancyButtonProps>(
  (props, ref) => {
    return (
      <InnierFancyButton {...props} ref={ref} />
    );
  }
);

export default FancyButton;

使用 ComponentPropsWithoutRef 优化类型定义

InnierFancyButtonProps类型定义还可以优化一下,其实 FancyButtonProps 这个类型有点多余,可以使用 ComponentPropsWithoutRef 这个泛型类型优化掉。

diff 复制代码
import React, { useImperativeHandle, forwardRef, createRef } from 'react';

- interface FancyButtonProps {
-  label: string;
-  onClick?: () => void;
- }

export interface FancyButtonRef {
  focus: () => void;
}

- interface InnierFancyButtonProps extends FancyButtonProps {
+ interface InnierFancyButtonProps {
  ref: React.ForwardedRef<FancyButtonRef>
+ label: string;
+ onClick?: () => void;
}

const InnierFancyButton: React.FC<InnierFancyButtonProps> = ({ ref, label, onClick }) => {
  const buttonRef = createRef<HTMLButtonElement>();

  useImperativeHandle(ref, () => ({
    focus: () => {
      buttonRef.current?.focus();
    },
  }));

  return (
    <button ref={buttonRef} onClick={onClick}>
      {label}
    </button>
  );
};

- const FancyButton = forwardRef<FancyButtonRef, FancyButtonProps>(
+ const FancyButton = forwardRef<FancyButtonRef, ComponentPropsWithoutRef<typeof InnierFancyButton>>(
  (props, ref) => {
    return (
      <InnierFancyButton {...props} ref={ref} />
    );
  }
);

export default FancyButton;
相关推荐
iphone1083 分钟前
一次编码,多端运行:HTML5多终端调用
前端·javascript·html·html5
老坛00121 分钟前
2025决策延迟的椭圆算子分析:锐减协同工具的谱间隙优化
前端
老坛00122 分钟前
从记录到预测:2025新一代预算工具如何通过AI实现前瞻性资金管理
前端
今禾24 分钟前
" 当Base64遇上Blob,图像转换不再神秘,让你的网页瞬间变身魔法画布! "
前端·数据可视化
华科云商xiao徐29 分钟前
高性能小型爬虫语言与代码示例
前端·爬虫
十盒半价30 分钟前
深入理解 React useEffect:从基础到实战的全攻略
前端·react.js·trae
攀登的牵牛花30 分钟前
Electron+Vue+Python全栈项目打包实战指南
前端·electron·全栈
iccb101331 分钟前
我是如何实现在线客服系统的极致稳定性与安全性的
前端·javascript·后端
一大树32 分钟前
Vue3祖孙组件通信方法总结
前端·vue.js
不要进入那温驯的良夜33 分钟前
跨平台UI自动化-Appium
前端