正如标题所述,我找不到正确的类型。
我已经检查了 DevTools 和我的每个组件,以编程方式查看 HAS Component.type.displayName
.type
对于不是 ElementType
的任何内容是一个函数。
节点的类型是 React.isValidElement 的返回类型,像这样提取 Parameters<typeof React.isValidElement>
,因为我不能确定它是什么。
有问题的部分:
const node = SomeThingUnknown as Parameters<typeof React.isValidElement>;
const type = ((node as unknown) as React.ReactElement<React.FunctionComponent>).type;
const displayName = typeof type === "function" ? type.displayName || type.name || "Unknown" : type;
最后一行取自 react repo 。所以我知道它有效。node
,在 VS Code 中是:const type: string | ((props: any) => React.ReactElement<any, string | ... | (new (props: any) =>
React.Component<any, any, any>)> | null) | (new (props: any) => React.Component<any, any, any>)
当我将鼠标悬停在 displayName
上时的错误是:Property 'displayName' does not exist on type 'JSXElementConstructor<any>'.
Property 'displayName' does not exist on type '(props: any) =>
ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null'.
最佳答案
尝试使用 Component.type.name
而不是 Component.type.displayName
关于javascript - 我找不到 `displayName` 的匹配 TypeScript 类型作为 `type` 的 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65793723/