TypeScript中父组件Props采用嵌套子组件Props接口是否可行?
这种写法完全合理,甚至更推荐!
嘿,作为TypeScript新手能想到这种嵌套Props的写法,真的很赞!这种{ title: TitleProps; subtitle: SubtitleProps; }的定义方式不仅合理,在很多场景下比扁平化的titleText/subtitleText更实用,原因有这几点:
- 语义更直观:直接用
title和subtitle对应子组件的Props,一眼就能看明白每个字段属于哪个子组件,比零散的xxxText命名更清晰,代码可读性更高。 - 扩展性极强:如果以后你的
Title或Subtitle组件需要新增属性(比如给Title加size、color,给Subtitle加italic),你只需要修改子组件的Props接口,父组件的TitleSubtitleProps完全不用改动,直接传递整个对象就行,维护成本低很多。 - TypeScript校验更精准:这种写法能直接复用子组件的类型定义,TypeScript会自动校验
title和subtitle是否符合对应子组件的Props要求,避免出现字段遗漏或类型不匹配的问题。
给你举个完整的代码示例,看看实际怎么用:
// 子组件Props定义 interface TitleProps { text: string; } interface SubtitleProps { text: string; } // 父组件Props定义 interface TitleSubtitleProps { title: TitleProps; subtitle: SubtitleProps; } // 子组件实现 const Title = ({ text }: TitleProps) => <h1 className="title">{text}</h1>; const Subtitle = ({ text }: SubtitleProps) => <h2 className="subtitle">{text}</h2>; // 父组件实现 const TitleSubtitle = ({ title, subtitle }: TitleSubtitleProps) => ( <div className="title-group"> {/* 使用扩展运算符传递整个Props对象 */} <Title {...title} /> <Subtitle {...subtitle} /> </div> ); // 调用父组件的方式 <TitleSubtitle title={{ text: "我的第一篇TypeScript文章" }} subtitle={{ text: "从组件Props开始入门" }} />
如果以后Title组件要加个size属性,只需要更新TitleProps:
interface TitleProps { text: string; size: 'small' | 'medium' | 'large'; }
然后调用的时候直接传:
<TitleSubtitle title={{ text: "我的第一篇TypeScript文章", size: 'medium' }} subtitle={{ text: "从组件Props开始入门" }} />
父组件的代码完全不用改,是不是很方便?
内容的提问来源于stack exchange,提问作者user14358266
相关产品推荐
相关产品推荐

