如何在TypeScript编写的React组件中渲染带自定义属性的Grid子项
如何在TypeScript React中为封装的Grid组件子项传递自定义属性
你遇到的核心问题是没有用你封装的Wrapper.Item来包裹实际的子组件(比如Button)——你的Wrapper本身只是渲染一个Grid容器,而width属性是需要传给Wrapper.Item这个子组件的,它才是负责生成带列宽设置的Grid item元素的。
第一步:修正组件使用方式
你需要把每个Button用Wrapper.Item包裹起来,这样就能给Wrapper.Item传递width属性了:
<Wrapper> <Wrapper.Item width={6}> <Button>Done</Button> </Wrapper.Item> <Wrapper.Item width={6}> <Button>Cancel</Button> </Wrapper.Item> </Wrapper>
这样Wrapper.Item就会接收width属性,渲染出对应xs列宽的Grid item,再把Button作为它的children渲染进去,就能完美实现列宽控制了。
第二步:优化TypeScript类型(可选但推荐)
为了避免以后再犯直接传递普通组件的错误,你可以修改IWrapperProps的children类型,强制要求子项必须是Wrapper.Item类型的元素,让TypeScript在编译阶段就给出提示:
// 修改IWrapperProps的children类型,限制为Wrapper.Item元素 export interface IWrapperProps { children: React.ReactElement<IComponentItem> | React.ReactElement<IComponentItem>[]; } export interface IComponentItem { width: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12; children: JSX.Element | JSX.Element[]; } const Wrapper = ({ children }: IWrapperProps) => { const classes = useStyles(); return ( <Grid container spacing={1} direction="row" > {children} </Grid> ); }; Wrapper.Item = ({ width, children }: IComponentItem) => { const classes = useStyles(); return ( <Grid item xs={width} className={classes.contentContainers}> {children} </Grid> ); }; export default Wrapper;
这样当你再直接把Button传给Wrapper时,TypeScript就会报错,提示你必须使用Wrapper.Item来包裹子组件,从根源上避免使用错误。
你的封装思路是完全正确的:用Wrapper做容器,Wrapper.Item做带自定义属性的子项容器,只要调整使用时的嵌套层级就能解决问题~
内容的提问来源于stack exchange,提问作者PineCone
相关产品推荐
相关产品推荐

