【问题标题】:Default generic on dynamic component (ReactTS)动态组件上的默认泛型 (ReactTS)
【发布时间】:2019-05-21 14:15:18
【问题描述】:

我的问题有点像我之前的问题: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 }

【问题讨论】:

    标签: reactjs typescript typescript-typings


    【解决方案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="" />
    

    【讨论】:

    • 伙计,你是绝对的救世主!因为我对 TS 有点陌生,所以我不知道我能做到这一点(即使我知道,很可能也不会想出这个大声笑)再次感谢!
    猜你喜欢
    • 2019-10-07
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-14
    • 2022-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多