【发布时间】:2020-01-28 13:11:16
【问题描述】:
React 组件通常会接受一些 props 并将其传递给它们的子组件。如果由于孩子的defaultProps 指定了孩子身上的一个或多个道具是可选的,那么如何为正确接受自己和孩子道具的父母定义type 或interface?
考虑以下说明性示例:
interface ParagraphProps {
body: string,
imgSrc: string,
}
interface SectionProps extends ParagraphProps {
title: string,
}
class Paragraph extends React.Component<ParagraphProps> {
static defaultProps = {
imgSrc: '../images/section-break.jpg',
};
render() {
const { body, imgSrc } = this.props;
return (
<p>{body}</p>
{!!imgSrc && <img src={imgSrc}>}
);
}
}
class Section extends React.Component<SectionProps> {
render() {
const { title, ...rest } = this.props;
return (
<section>
<h1>{title}</h1>
<Paragraph {...rest}>
</section>
);
}
}
现在,声明 <Section title='T' body='B'> 将导致错误:
类型 [...] 中缺少属性“imgSrc”
如果我们改为为 Section 定义 props,如下所示:
interface SectionProps {
title: string,
}
type FullSectionProps = Partial<SectionProps & PartialProps>;
然后我们发现现在title和body是可选的,这不是我们想要的。
在剩余 DRY 的同时,我应该如何指定 Section 的 props 以规定 title 和 body 是必需的,imgSrc 是可选的?
【问题讨论】:
标签: reactjs typescript typescript3.0