我的问题与上一个问题类似:ReactTS extend type by dynamic Component Props?
所以可以说我接下来的几行:
type Base = {
baseProp: ...
}
type Extend = {
extendProp: ...
}
// use this if "as" undefined
type DefaultPropsToExtend = {
defaultToExtendProp: ...
}
declare const ExtendedComponent: React.FC<Extend>
declare const DefaultExtendedComponent: React.FC<DefaultPropsToExtend>
function Base<T = DefaultPropsToExtend>(props: BaseProps & { as: React.ComponentType<T> } & T): React.ReactElement {
const Wrapper = props.as
return <Wrapper />
}
所以我在拨打下一行时期望的是:
<Base /> // props can be => { baseProp, defaultToExtendProp }
What props actually I am seeing => { baseProp }
If I am doing the next then things working property, but this way I need to be explicit about the default "as" every time.
<Base as={DefaultToExtendComponent} /> // => { baseProp, defaultToExtendProp }
答案 0 :(得分:1)
最好的选择可能是使用重载。一个重载可以是通用的,并且可以接受任何组件。其他重载可以具有默认值:
type BaseProps = {
baseProp: string
}
type Extend = {
extendProp: number
}
// use this if "as" undefined
type DefaultPropsToExtend = {
defaultToExtendProp: number
}
declare const ExtendedComponent: React.FC<Extend>
declare const DefaultExtendedComponent: React.FC<DefaultPropsToExtend>
function Base(props: BaseProps & DefaultPropsToExtend): React.ReactElement
function Base<T>(props: BaseProps & { as: React.ComponentType<T> } & T): React.ReactElement
function Base<T = DefaultPropsToExtend>(props: BaseProps & { as?: React.ComponentType<T> } & T): React.ReactElement {
const Wrapper = props.as || (DefaultExtendedComponent as unknown as React.ComponentType<T>)
return <Wrapper {...props as T}/>
}
let a = <Base baseProp="" defaultToExtendProp={0} />
let a2 = <Base as={DefaultExtendedComponent} defaultToExtendProp={0} baseProp="" />