[英]Getting TS error, "Property 'children' does not exist on type 'TPage'"
I have a component like this:我有一个这样的组件:
type TPage = {
title: string;
};
const Page = React.memo(({ children, title, ...rest }: TPage) => {
return (
<div {...rest}>
<div>{title}</div>
{children}
</div>
);
});
And I use it as,我用它作为,
<Page
title="Title"
style={{
minHeight: "100vh",
display: "flex",
alignItems: "center",
justifyContent: "center",
flexDirection: "column"
}}
>
<div>Some content</div>
</Page>
This throws an error,这会引发错误,
const Page = React.memo(({ children, title, ...rest }: TPage) => {
^^^^^^^^
Property 'children' does not exist on type 'TPage'
I've tried fixing it by changing TType
to,我尝试通过将
TType
更改TType
来修复它,
type TPage = React.PropsWithChildren<{
title: string;
children: React.ReactNode;
}>;
This fixed the issue with children
, but it started complaining for the style
prop, saying这解决了
children
的问题,但它开始抱怨style
道具,说
Property 'style' does not exist on type 'IntrinsicAttributes
& { title: string; children: ReactNode; } & { children?: ReactNode; }'
What am I doing wrong here?我在这里做错了什么?
TS won't check what you're doing with the props (using title
and children
then passing the rest to a div) and won't let you use any props that aren't in the type. TS 不会检查您对道具所做的事情(使用
title
和children
然后将其余部分传递给 div)并且不会让您使用任何不在类型中的道具。 If you wanted to extend the functionality of the div
use the JSX
type in a union with your props.如果您想扩展
div
的功能,请将JSX
类型与您的道具结合使用。
type TPage = JSX.IntrinsicElements["div"] & {
title: string;
};
As far as I know functional component in react TypeScript should look like this:据我所知,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
Now after you add the FC you should get the children as a prop better to write this what.现在,在添加 FC 之后,您应该将孩子作为道具更好地编写此内容。 now for you style error it due to missing style prop in the type write the type like this:
现在,由于类型中缺少样式道具,您的样式错误请编写如下类型:
type TPage = {
title: string;
style: React.CSSProperties;
};
as you can see the FC get generic type to get to props think like prop-types in react javascript but it just don't gonna let you run if you pass wrong type to a props instead of pop a console error正如你所看到的,FC 获得通用类型来获取 props 就像 react javascript 中的 prop-types 一样,但是如果你将错误的类型传递给 props 而不是弹出控制台错误,它就不会让你运行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.