export const PageViewTracker = ({ children }: ReactNode): ReactElement => {
usePageView();
return children;
};
问题:
此函数返回错误» “ReactNode”类型上不存在属性“子项” «
我的解决方法:
我尝试了几种类型,但只有 任何 不是我想要的作品。通常我将 ReactNode 用于儿童道具并且效果很好。在这种情况下,TypeScript 似乎有问题。
原文由 Christoph 发布,翻译遵循 CC BY-SA 4.0 许可协议
反应 >=18
在 React 18 中,
FunctionalComponent
接口已更改为:请注意,在 React 18 之后,FunctionalComponent 的
PropsWithChildren
类型中省略了props
类型,这意味着您必须自己包含children
:他们删除隐式
children
的原因可以在 这里 找到。 (React 18 的类型定义发布说明的 来源)。PropsWithChildren
类型在 React 的类型中仍然可用,所以如果你仍然想选择children
作为道具,就像 React 18 之前的版本一样,你仍然可以这样做:PropsWithChildren
的类型定义为:反应 <=17
您收到该错误的原因是因为您将“ReactNode”接口提供给对象(
{}: Type
)。children
本身就是 ReactNode 类型:type PropsWithChildren<P> = P & { children?: ReactNode };
您应该为 PageViewTracker 提供
FunctionComponent
(或其别名FC
)类型。它具有以下界面:
因此默认情况下,它接受
children
类型为“ReactNode”的道具。