如何用TypeScript实现多层嵌套的复合组件?
实现多层嵌套的TypeScript复合组件模式
组件挂载实现
要实现多层嵌套的复合组件,核心逻辑是将子组件依次挂载到父组件的属性上,层级嵌套的本质就是逐层挂载:
- 先定义所有独立的组件函数
- 将下一级组件赋值给上一级组件的对应属性
示例代码:
// 定义基础组件 const Card = () => <div className="card"></div>; const CardContent = () => <div className="card-content"></div>; const CardContentAction = () => <div className="card-content-action"></div>; const CardContentActionOther = () => <div className="card-content-action-other"></div>; // 逐层挂载建立嵌套关系 Card.Content = CardContent; Card.Content.Action = CardContentAction; Card.Content.Action.Other = CardContentActionOther;
TypeScript类型定义
要让TypeScript正确识别这种多层嵌套的属性关系,需要为每个组件定义包含子组件属性的类型,从最内层向外逐层定义:
1. 定义最内层组件类型
先处理最底层的组件,若它还有子组件,需在类型中声明:
// 定义最内层Action组件的类型,包含Other子组件 type CardContentActionType = React.FC & { Other: typeof CardContentActionOther; };
2. 定义中间层级组件类型
接着定义上一层组件的类型,包含下一级组件的属性:
// 定义Content组件的类型,包含Action子组件 type CardContentType = React.FC & { Action: CardContentActionType; };
3. 定义顶层组件类型
最后定义最外层组件的类型,包含它的直接子组件属性:
// 定义Card组件的类型,包含Content子组件 type CardType = React.FC & { Content: CardContentType; };
4. 为组件指定类型
将定义好的类型赋值给对应组件,让TypeScript能正确推断嵌套属性:
// 为组件绑定类型 const Card = () => <div className="card"></div> as CardType; const CardContent = () => <div className="card-content"></div> as CardContentType; const CardContentAction = () => <div className="card-content-action"></div> as CardContentActionType; const CardContentActionOther = () => <div className="card-content-action-other"></div> as React.FC; // 挂载层级关系 Card.Content = CardContent; Card.Content.Action = CardContentAction; Card.Content.Action.Other = CardContentActionOther;
完整使用示例
现在可以按照预期的嵌套结构使用组件:
export const Screen = () => { return ( <Card> <Card.Content> <Card.Content.Action> <Card.Content.Action.Other> 多层嵌套的内容 </Card.Content.Action.Other> </Card.Content.Action> </Card.Content> </Card> ); };
内容的提问来源于stack exchange,提问作者Cristian Flórez
相关产品推荐
相关产品推荐

