我创建了以下组件:
export default function IdeaInfos({children}: { children: ReactElement<IdeaInfoProp, typeof IdeaInfo> }) {
const classes = useStyles()
return (
<Grid container
justify="center"
alignItems="center"
className={classes.wrapper}>
{children}
</Grid>
)
}
组件应该限制传递的孩子的类型,在这种情况下是(这是我期望的方式),孩子只能是IdeaInfo
和属性IdeaInfoProp
的组件。< /p>
但是,当我使用组件 IdeaInfos
<IdeaInfos>
<Typography>
Hello
</Typography>
</IdeaInfos>
也可以将 Typography
作为 IdeaInfos
的子代传递。
为什么编译器不抱怨?我已经完成了类型限制。
更新
抱歉,我忘记了共享 IdeaInfoProp
和 IdeaInfo
:
export interface IdeaInfoProp {
icon: string,
text: string,
textBgColor: string,
alt: string
reverse?: boolean,
}
export default function IdeaInfo({icon, text, textBgColor, alt, reverse = false}: IdeaInfoProp) {
const classes = useStyles()
return (
<Grid item container xs={12} direction={reverse ? "row-reverse" : "row"}>
<Grid item xs={12} md={6} style={{background: `${textBgColor}`}}>
<Typography className={classes.text} variant="h4">
{text}
</Typography>
</Grid>
<Grid
item
xs={12}
md={6}
container
justify="center"
alignItems="center"
>
<img src={icon} alt={alt} className={classes.mediaIcon}/>
</Grid>
</Grid>
)
}
我使用 Typography
只是为了演示,但它来自 https://material-ui.com/components/typography/#typography