React/Typescript 如何跨多层组件传递并定义class prop的类型
透传实现方案
前提说明
原有MyBanner组件的类型定义和接收逻辑不需要改动,保持原有实现即可:
// MyBanner/MyBanner.types.ts 原有逻辑不变 import { SerializedStyles } from '@emotion/react'; export type Class = Partial<Record<'root', SerializedStyles>>; export type Props = { class?: Class; };
步骤1:定义AnotherChild层的类型与透传逻辑
首先给AnotherChild组件定义Props,其class属性需要包含要透传给MyBanner的myBanner字段:
// AnotherChild/AnotherChild.types.ts import { SerializedStyles } from '@emotion/react'; import { Class as MyCustomBannerClass } from '../MyBanner/MyBanner.types'; // 如果AnotherChild自身也需要自定义样式,可以扩展root字段 type Class = Partial<Record<'root', SerializedStyles>> & { myBanner: MyCustomBannerClass; }; export type Props = { class: Class; };
然后在AnotherChild组件内部,把对应的myBanner样式传给MyBanner:
// AnotherChild组件内部逻辑 import MyBanner from '../MyBanner/MyBanner'; import { Props } from './AnotherChild.types'; const AnotherChild = (props: Props) => { // 其他组件逻辑 return <MyBanner class={props.class?.myBanner} /> }
步骤2:调整Child层的传参逻辑
Child层的原有类型定义不需要改动,只需要把原来直接传给MyBanner的参数,改成传给新增的AnotherChild即可:
// Child组件内部逻辑调整 import AnotherChild from './AnotherChild/AnotherChild'; import { Props } from './Child.types'; // 原有Props定义不变 const Child = (props: Props) => { // 其他组件逻辑 // 把原来的<MyBanner class={props.class?.myBanner} />替换为下行 return <AnotherChild class={props.class} /> }
效果验证
完成以上调整后,外层调用的写法完全不需要修改:
<Child class={{ myBanner: styles.myBanner }} />
传入的样式会经过Child -> AnotherChild -> MyBanner三层透传生效,全程Typescript类型校验正常,无类型报错。如果后续需要新增其他透传的样式字段,只需要在各层的Class类型中同步新增对应字段即可,扩展成本极低。
内容的提问来源于stack exchange,提问作者meez
相关产品推荐
相关产品推荐

