TypeScript错误:类型'ReactNode'上不存在属性'children'

时间:2019-11-29 14:38:28

标签: reactjs typescript

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

    usePageView();

    return children;
};

问题:

此函数返回错误»类型为'ReactNode'的属性'children'不存在«

我的解决方案:

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

1 个答案:

答案 0 :(得分: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道具。

相关问题