FORMA

TypeScript

React 官方推荐 TypeScript。类型主要落在 Props事件RefHooks 返回值上。见 组件

函数组件 Props

tsx
type ButtonProps = {
  label: string;
  disabled?: boolean;
  onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
};

export function Button({ label, disabled, onClick }: ButtonProps) {
  return (
    <button type="button" disabled={disabled} onClick={onClick}>
      {label}
    </button>
  );
}

children 常用 React.ReactNode

带 children 的组件

tsx
type CardProps = {
  title: string;
  children: React.ReactNode;
};

泛型组件

tsx
type ListProps<T> = {
  items: T[];
  renderItem: (item: T) => React.ReactNode;
};

function List<T>({ items, renderItem }: ListProps<T>) {
  return <ul>{items.map((item) => <li key={String(item)}>{renderItem(item)}</li>)}</ul>;
}

常用类型

类型用途
React.FC可选;官方不强制,显式写 Props 更清晰
React.ComponentProps<"input">继承原生 input 全部属性
React.ComponentPropsWithoutRef<typeof Link>包装第三方组件 props
React.RefObject<HTMLDivElement>DOM ref

useRef

tsx
const inputRef = useRef<HTMLInputElement>(null);
inputRef.current?.focus();

事件

使用 React.ChangeEvent<HTMLInputElement> 等,避免 any

参考文献

以下链接在编写时均可正常访问:

Series

react

16 / 16

测试