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

Chr*_*oph 10 typescript reactjs

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

    usePageView();

    return children;
};
Run Code Online (Sandbox Code Playgroud)

问题:

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

我的解决方法:

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

Syl*_*lin 51

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

interface MyButtonProps {
  color: string;
  children?: React.ReactNode;
}
Run Code Online (Sandbox Code Playgroud)

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

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

来自文档


Yil*_*maz 23

对于“@types/react”:“17.0.43”,或小于 18

import { FunctionComponent } from "react";


const BaseLayout: FunctionComponent = ({ children }) => {
  return (
    <>      
    </>
  );
};

export default BaseLayout;
Run Code Online (Sandbox Code Playgroud)

对于“@types/react”> 18

interface BaseLayoutProps {
  children?: ReactNode;
}

const BaseLayout: FunctionComponent<BaseLayoutProps> = ({ children }) => {
  return (
    <>          
    </>
  );
};
Run Code Online (Sandbox Code Playgroud)

但对于某些情况,您仍然需要使用FunctionComponent. 例如:

interface ArtListProps {
  arts: Art[];
  children: FunctionComponent;
}

export default function ArtList({ arts, children }: ArtListProps) {
  return (
    <section className="grid md:grid-cols-1 lg:grid-cols-2 gap-4 mb-5">
      {/* this is called render prop */}
      {arts.map((art) => children(art))}
    </section>
  );
}
Run Code Online (Sandbox Code Playgroud)

如果你通过ReactNode,你会得到错误“type ReactNode is not callable`


Als*_*rda 15

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

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

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

export const PageViewTracker: React.FC = ({ children }) => {
   ...
}
Run Code Online (Sandbox Code Playgroud)

它具有以下界面:

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

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


nth*_*oli 7

你可以简单地这样写:

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

    usePageView();

    return children;
};
Run Code Online (Sandbox Code Playgroud)

请注意,我更改({ children }: ReactNode)({ children }: {children: ReactNode})


小智 6

import React from 'react';

interface Props {
  children?: React.ReactNode;
}

export const MenuLateral: React.FC<Props> = ({ children }) => {
  return (
    <>
      
      {children}
    </>
  );
};
Run Code Online (Sandbox Code Playgroud)