react typescript 备忘清单

181 阅读2分钟

基本的组件props

type AppProps = {
  message: string;
  count: number;
  disabled: boolean;
  /** array of a type! */
  names: string[];
  /** string literals to specify exact string values, with a union type to join them together */
  status: "waiting" | "success";
  /** an object with known properties (but could have more at runtime) */
  obj: {
    id: string;
    title: string;
  };
  /** array of objects! (common) */
  objArr: {
    id: string;
    title: string;
  }[];
  /** any non-primitive value - can't access any properties (NOT COMMON but useful as placeholder) */
  obj2: object;
  /** an interface with no required properties - (NOT COMMON, except for things like `React.Component<{}, State>`) */
  obj3: {};
  /** a dict object with any number of properties of the same type */
  dict1: {
    [key: string]: MyTypeHere;
  };
  dict2: Record<string, MyTypeHere>; // equivalent to dict1
  /** function that doesn't take or return anything (VERY COMMON) */
  onClick: () => void;
  /** function with named prop (VERY COMMON) */
  onChange: (id: number) => void;
  /** function type syntax that takes an event (VERY COMMON) */
  onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
  /** alternative function type syntax that takes an event (VERY COMMON) */
  onClick(event: React.MouseEvent<HTMLButtonElement>): void;
  /** any function as long as you don't invoke it (not recommended) */
  onSomething: Function;
  /** an optional prop (VERY COMMON!) */
  optional?: OptionalType;
  /** when passing down the state setter function returned by `useState` to a child component. `number` is an example, swap out with whatever the type of your state */
  setState: React.Dispatch<React.SetStateAction<number>>;
};

在 Typescript 中,通常最好为对象使用特定类型。在大多数情况下,这意味着像{ id: string; name: string }是字面量类型。在对象没有固定结构的情况下,您可能需要索引签名(可能使用 Record 速记) 如果值是某种特定类型,但键可以更改。 或者如果对象结构或多或少是一个任意的黑盒子则使用泛型

对象的另一种方法是 Map 数据结构,但这在 React 中使用有点不常见,因为 React 更喜欢不可变地更改数据(例如 setUser({...user, name: newName})),而 Maps 是可变数据结构。

“模糊”对象类型,如 object、{} 相当小众,应该很少使用,并且功能可能与您预期的不同。 object 是任何非原始值:这包括函数、数组和构造函数之类的东西,而不仅仅是“简单”的对象。并且 {} 可能更好地被认为是“一个没有必需属性的接口”,而不是“一个空对象”——在实践中,这种类型允许除 null 或 undefined 之外的任何东西。 Object 的行为与 {} 相同,基本上从未使用过。

非常有用的 React Prop Type

export declare interface AppProps {
  children?: React.ReactNode; // best, accepts everything React can render
  childrenElement: JSX.Element; // A single React element
  style?: React.CSSProperties; // to pass through style props
  onChange?: React.FormEventHandler<HTMLInputElement>; // form events! the generic parameter is the type of event.target
  //  more info: https://react-typescript-cheatsheet.netlify.app/docs/advanced/patterns_by_usecase/#wrappingmirroring
  props: Props & React.ComponentPropsWithoutRef<"button">; // to impersonate all the props of a button element and explicitly not forwarding its ref
  props2: Props & React.ComponentPropsWithRef<MyButtonWithForwardRef>; // to impersonate all the props of MyButtonForwardedRef and explicitly forwarding its ref
}

类型还是接口

您可以使用 Types 或 Interfaces 来键入 Props 和 State,因此自然会出现问题 - 您使用哪个?

AspectTypeInterface
可以描述函数
可以描述构造函数
可以描述元组
接口可以扩展它⚠️
类可以扩展它🚫
类可以实现它 ( implements)⚠️
可以与同类相交⚠️
可以与同类中的另一个建立联盟🚫
可用于创建映射类型🚫
可以用映射类型映射
在错误消息和日志中展开🚫
可以增强🚫
可以递归⚠️