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;
相关推荐
只可远观几秒前
Flutter Android打包和发布Build APK
前端·flutter·dart
BillKu17 分钟前
Vue3 + TypeScript 操作第三方库(Element Plus 的 ElTable)的内部属性
前端·javascript·typescript
嘉小华18 分钟前
深入浅出Android SurfaceView:高性能绘制
前端
土豆125023 分钟前
React-PDF 完全指南:在你的应用中优雅地展示 PDF
react.js
古夕27 分钟前
webpack 之 Tree-shaking
前端·面试·webpack
沐森28 分钟前
websockt vs sse
前端·ai编程
朕么办29 分钟前
微信原生开发的程序员有福了,推荐两款插件让你VScode支持WXML Emmet
前端
风铃喵游30 分钟前
Axion: 一次搞定axios请求库的各种能力封装
前端
受之以蒙30 分钟前
Rust+Wasm利器:用wasm-pack引爆前端性能!
前端·rust·webassembly
Dream耀31 分钟前
解锁JavaScript函数式编程的核心技能
前端·javascript·设计模式