![](/img/trans.png)
[英]Getting TS error with Redux dispatch action, `Property does not exist on type`
[英]Getting TS error, "Property 'children' does not exist on type 'TPage'"
我有一个这样的组件:
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
更改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; }'
我在这里做错了什么?
TS 不会检查您对道具所做的事情(使用title
和children
然后将其余部分传递给 div)并且不会让您使用任何不在类型中的道具。 如果您想扩展div
的功能,请将JSX
类型与您的道具结合使用。
type TPage = JSX.IntrinsicElements["div"] & {
title: string;
};
据我所知,react TypeScript 中的功能组件应该是这样的:
type TPage = {
title: string;
};
const Page:FC<TPage> = React.memo(({ children, title, ...rest }) => {
return (
<div {...rest}>
<div>{title}</div>
{children}
</div>
);
});
//FunctionalComponent can be also insted of FC
现在,在添加 FC 之后,您应该将孩子作为道具更好地编写此内容。 现在,由于类型中缺少样式道具,您的样式错误请编写如下类型:
type TPage = {
title: string;
style: React.CSSProperties;
};
正如你所看到的,FC 获得通用类型来获取 props 就像 react javascript 中的 prop-types 一样,但是如果你将错误的类型传递给 props 而不是弹出控制台错误,它就不会让你运行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.