接受任何类型的 React 组件作为 prop 的 Typescript 类型是什么?

kio*_*opi 22 typescript reactjs

我有一个组件可以接受另一个组件作为道具。

非常简单的例子:

interface Props {
  Comp: React.ComponentClass<unknown> | React.SFC<unknown>
}

const MyComp: React.FC<props> = ({ Comp }) => {
  return React.createElement(Comp)
}
Run Code Online (Sandbox Code Playgroud)

Comp 接受函数组件、基于类的组件等的最简单类型是什么?

createElement 的类型定义使其看起来相当复杂 https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/v16/index.d.ts#L286

Lin*_*ste 42

React.ComponentType

React.ComponentType<P>是带有 props 的类组件 ( React.ComponentClass<P>) 或函数组件 (React.FunctionComponent<P>又名)的类型。React.FC<P>P

(仅供参考,React.ReactNodeReact.ReactElement是组件返回的 JSX 的类型 - 不适用于可调用组件)

打字 Comp 的道具

您不想<unknown>在您的Props类型中使用。您想要声明该组件仅需要您在调用时提供的道具React.createElement(Comp)(您也可以使用 JSX 和return <Comp/>)。在这种情况下,您没有提供任何道具,因此它将是React.ComponentType<{}>或只是React.ComponentType因为{}是 的默认值P

interface Props {
  Comp: React.ComponentType;
}

const MyComp: React.FC<Props> = ({ Comp }) => {
  return <Comp />
}
Run Code Online (Sandbox Code Playgroud)

一些道具:

interface Props {
  Comp: React.ComponentType<{someKey: string}>;
}

const MyComp: React.FC<Props> = ({ Comp }) => {
  return <Comp someKey="someValue" />
}
Run Code Online (Sandbox Code Playgroud)

如果您Comp在未提供的情况下调用,则会收到错误消息someKey,这很好!调用时不会出现该错误,React.createElement(Comp)因为由于某种原因该props参数是可选的。所以我认为 JSX 方法更好。