TypeScript 错误:“ReactNode”类型上不存在属性“子项”

新手上路,请多包涵
export const PageViewTracker = ({ children }: ReactNode): ReactElement => {

    usePageView();

    return children;
};

问题:

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

我的解决方法:

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

原文由 Christoph 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.9k
2 个回答

反应 >=18

在 React 18 中, FunctionalComponent 接口已更改为:

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

请注意,在 React 18 之后,FunctionalComponent 的 PropsWithChildren 类型中省略了 props 类型,这意味着您必须自己包含 children

 interface Props {
  children: React.ReactNode;
}

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

他们删除隐式 children 的原因可以在 这里 找到。 (React 18 的类型定义发布说明的 来源)。

PropsWithChildren 类型在 React 的类型中仍然可用,所以如果你仍然想选择 children 作为道具,就像 React 18 之前的版本一样,你仍然可以这样做:

 import { PropsWithChildren } from 'react';

interface Props {
  foo: string;
}

export const PageViewTracker: React.FC<PropsWithChildren<Props>> = ({ children, foo }) => {
}

PropsWithChildren 的类型定义为:

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


反应 <=17

您收到该错误的原因是因为您将“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;
}

因此默认情况下,它接受 children 类型为“ReactNode”的道具。

原文由 Alserda 发布,翻译遵循 CC BY-SA 4.0 许可协议

重要说明:在 React 18.0.0 之后,它们会让您在每个 FC 界面中包含子项。

 interface MyButtonProps {
  color: string;
  children?: React.ReactNode;
}

然后你可以像旧版本一样传递道具。

 const Button:React.FC<MyButtonProps> = (props) => {
    //use children with {props.children} just like before
}

来自 文档

原文由 Thomas Franklin 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进