跳转到内容
代码片段·免费

React 与 TypeScript 代码片段

20 个用于 .tsx 文件的 React 代码片段:带类型的 props、useReducer 的 action、带清理的 effect、带类型的 context hook、useLocalStorage、错误边界和 Testing Library 测试。文件所需的 React import 需要你自己添加。

免费安装。

如果你的 Android 设备上装了 PocketCode,这会在应用里打开此页面。

预览

20 个中的 5 个

Component with typed propstfc

Function component with a props type

type ${1:Button}Props = {
  ${2:label}: string;
  onClick?: () => void;
};

export function ${1:Button}({ ${2:label}, onClick }: ${1:Button}Props) {
  return <${3:button} onClick={onClick}>{${2:label}}</${3:button}>;
}

Component with childrentfcc

Wrapper component that renders its children

import type { ReactNode } from "react";

export function ${1:Card}({ children }: { children: ReactNode }) {
  return <div className="${2:card}">{children}</div>;
}

useState with a typeustate

State hook with an explicit type

const [${1:value}, set${2:Value}] = useState<${3:string}>(${4:""});

Reducer with typed actionsureducer

State and action types plus a reducer for useReducer

type ${1:State} = { ${2:count}: number };
type ${3:Action} = { type: "${4:increment}" } | { type: "${5:reset}" };

function ${6:reducer}(state: ${1:State}, action: ${3:Action}): ${1:State} {
  switch (action.type) {
    case "${4:increment}":
      return { ...state, ${2:count}: state.${2:count} + 1 };
    case "${5:reset}":
      return { ${2:count}: 0 };
  }
}

useEffect with cleanupueffect

Effect that undoes its work when the component unmounts or deps change

useEffect(() => {
  ${1:const id = setInterval(tick, 1000);}
  return () => {
    ${2:clearInterval(id);}
  };
}, [$3]);

1.0.0 的变更

首个版本。

相关