Mat*_*ats 14 javascript type-conversion typescript reactjs
正如标题所述,我找不到正确的类型。我已经检查了 DevTools 和我以编程方式查看的每个组件 HAS Component.type.displayName
。对于任何type
不是 a 的东西来说,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;
Run Code Online (Sandbox Code Playgroud)
最后一行取自React存储库。所以我知道它有效。
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>)
Run Code Online (Sandbox Code Playgroud)
当我将鼠标悬停在上面时出现的错误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'.
Run Code Online (Sandbox Code Playgroud)
Mat*_*ats -2
我想我解决了:
export function extractType(node: unknownElement): Function | string {
return ((node as unknown) as React.ReactElement).type;
}
export function extractDisplayName(type: React.FunctionComponent): string {
return type.displayName || type.name || "Unknown";
}
Run Code Online (Sandbox Code Playgroud)
然后调用它:
const type = extractType(node);
if (typeof type === "function") {
const displayName = extractDisplayName((type as unknown) as React.FunctionComponent);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4823 次 |
最近记录: |