Мой вопрос похож на мой предыдущий: Тип расширения ReactTS с помощью динамических реквизитов компонентов?
Итак, скажем, у меня есть следующие строки:
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 }
🤔 А знаете ли вы, что...
React Native - это фреймворк, основанный на React, для создания мобильных приложений для iOS и Android.
Вероятно, лучший вариант — использовать перегрузки. Одна перегрузка может быть универсальной и принимать любой компонент. Другая перегрузка может иметь значение по умолчанию:
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 = "" />