javascript - 收到 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; }'
我在这里做错了什么?
解决方案
TS 不会检查您对道具所做的事情(使用title
然后children
将其余部分传递给 div),并且不会让您使用任何不在类型中的道具。如果您想扩展div
使用该JSX
类型与您的道具联合的功能。
type TPage = JSX.IntrinsicElements["div"] & {
title: string;
};
推荐阅读
- python - 如何在递归函数中保持值不变?
- google-cloud-platform - CloudRun 正在超过最大实例数(共 1 个)
- go - 使用等待组的 Golang 工作者
- javascript - 如何添加不与更新内容功能冲突的自动图像幻灯片放映
- python - pd.DataFrame 上的 for 循环继续运行,但在 100 次迭代后停止工作
- php - 如何插入或更新来自不同表的记录
- arrays - C char 数组在赋值循环后丢失指针
- azure-data-factory - Azure 数据工厂 - 不安然后删除
- c# - 如何在 C# 中使用 sendgrid 添加回复
- python - 我喜欢从双重列表中消除重复的组件,然后合并双重列表