【发布时间】:2018-05-27 15:27:05
【问题描述】:
有没有办法将另一个组件附加到一个已经被键入为 ComponentType 的组件?
例如:
type Props = {
name: string,
}
const Header: ComponentType<Props> = ({ props }) => (<h1>{name}</h1>)
const SubHeader: ComponentType<Props> = ({ props }) => (<h2>{name}</h2>)
Header.SubHeader = SubHeader // this is causes a flow error due to ComponentType
这个例子有点做作,但在使用 HOC 或 styled-components 时,有时需要手动强制为 ComponentType。
【问题讨论】:
-
是的,交叉点就可以了:
const Header: ComponentType<Props> & { SubHeader?: ComponentType<Props> } -
嗯,我认为这通常会起作用,但使用
styled-components会破坏它,因为他们对styled()的定义拒绝所有交集类型。我会问他们该怎么做,但这是回答:)。你们有谁想回答吗?