【问题标题】:TypeScript error: Property 'children' does not exist on type 'ReactNode'TypeScript 错误:“ReactNode”类型上不存在属性“子项”
【发布时间】:2020-03-25 03:59:52
【问题描述】:
export const PageViewTracker = ({ children }: ReactNode): ReactElement => {

    usePageView();

    return children;
};

问题:

此函数返回错误 »“ReactNode”类型上不存在属性“children”«

我的解决方法:

我尝试了几种类型,但只有 any 有效,这不是我想要的。通常我将 ReactNode 用于儿童道具并且效果很好。在这种情况下,TypeScript 似乎有问题。

【问题讨论】:

  • 你想要({ children }: { children: ReactNode })。您编写它的方式是尝试将解构的 props 对象键入为 ReactNode,而 props 显然不是。
  • 完全去掉孩子的括号

标签: reactjs typescript


【解决方案1】:

您收到该错误的原因是您将“ReactNode”接口提供给对象 ({}: Type)。 children 本身属于 ReactNode 类型:

type PropsWithChildren<P> = P & { children?: ReactNode };

您应该为 PageViewTracker 提供 FunctionComponent(或其别名 FC)类型。

export const PageViewTracker: React.FC = ({ children }) => {
   ...
}

有如下接口:

interface FunctionComponent<P = {}> {
    (props: PropsWithChildren<P>, context?: any): ReactElement | null;
    propTypes?: WeakValidationMap<P>;
    contextTypes?: ValidationMap<any>;
    defaultProps?: Partial<P>;
    displayName?: string;
}

所以默认情况下它接受类型为“ReactNode”的children prop。

【讨论】:

  • 你不一定是错的,但这不是 OP 发布的代码的问题......
【解决方案2】:

你可以这样写:

export const PageViewTracker = ({ children }: {children: ReactNode}): ReactElement => {

    usePageView();

    return children;
};

注意我把({ children }: ReactNode)改成({ children }: {children: ReactNode})

【讨论】:

  • 这按预期工作,但这两者有什么区别?
猜你喜欢
  • 2021-09-06
  • 1970-01-01
  • 2016-09-07
  • 2020-09-03
  • 1970-01-01
  • 1970-01-01
  • 2023-02-21
  • 1970-01-01
  • 2019-04-12
相关资源
最近更新 更多