首页 > 解决方案 > 收到 TS 错误,“类型 'TPage' 上不存在属性 'children'”

问题描述

我有一个这样的组件:

type TPage = {
  title: string;
};
const Page = React.memo(({ children, title, ...rest }: TPage) => {
  return (
    <div {...rest}>
      <div>{title}</div>
      {children}
    </div>
  );
});

我用它作为,

    <Page
      title="Title"
      style={{
        minHeight: "100vh",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        flexDirection: "column"
      }}
    >
      <div>Some content</div>
    </Page>

这会引发错误,

const Page = React.memo(({ children, title, ...rest }: TPage) => {
                           ^^^^^^^^
Property 'children' does not exist on type 'TPage'

我已经尝试通过更改TType为来修复它,

type TPage = React.PropsWithChildren<{
  title: string;
  children: React.ReactNode;
}>;

这解决了问题children,但它开始抱怨style道具,说

Property 'style' does not exist on type 'IntrinsicAttributes
  & { title: string; children: ReactNode; } & { children?: ReactNode; }'

我在这里做错了什么?

不错的浏览器-y7vjd

标签: javascriptreactjstypescript

解决方案


TS 不会检查您对道具所做的事情(使用title然后children将其余部分传递给 div),并且不会让您使用任何不在类型中的道具。如果您想扩展div使用该JSX类型与您的道具联合的功能。

type TPage = JSX.IntrinsicElements["div"] & {
  title: string;
};

推荐阅读