簡體   English   中英

如何在 React 高階組件上保留泛型?

[英]How can I preserve generics on a React higher-order component?

假設我想使用 React高階組件模式在我的 props 擊中我的組件之前對其進行轉換:

type UpstreamProps<X> = {
    foo?: number
    bar?: string
    baz:  X
}

type DownstreamProps<X> = {
    foo: number
    bar: string
    baz: X
    bix: string
}

function transform<X>(props: UpstreamProps<X>): DownstreamProps<X> {
    return {
        ...props,
        foo: props.foo || 0,
        bar: props.bar || '(unknown)',
        bix: `${props.foo}-${props.bar}-bix`
    }
}

在小部件定義中,我想使用下游(嚴格)道具:

function Parent<X>(props: DownstreamProps<X> & {formatter: (x: X) => string}) {
    return (
        <>
            foo = {props.foo}
            bar = {props.bar}
            baz = {props.formatter(props.baz)}
            bix = {props.bix}
        </>
    )
}

在呼叫站點,我應該能夠傳入上游(可選)道具:

<WrappedParent<number>
    baz={22}
    formatter={(x: number) => `my number squared is ${Math.pow(x, 2)}`}
/>

這與我編寫高階組件一樣接近,但我無法讓它與Parent / WrappedParent上的泛型很好地配合使用:

function withDownstreamProps<X, OtherProps>(
    WrappedComponent: React.ComponentType<DownstreamProps<X> & OtherProps>
) {
    return function({foo, bar, baz, ...otherProps}: UpstreamProps<X> & OtherProps) {
        return (
            <WrappedComponent
                {...otherProps}
                {...transform({foo, bar, baz})}
            />
        )
    }
}

export default withDownstreamProps(Parent) // doesn't keep generics

如何編寫和/或使用我的高階組件包裝器來保留WrappedParent上的泛型?

您要分配給WrappedParent的泛型類型應該給withDownstreamProps HOC 而不是結果組件:

export default withDownstreamProps<number>(Parent)

現在WrappedParentbaz屬性的類型將是number

如果我的回答有幫助,將不勝感激。

這樣的事情對你的情況有用嗎?:

type Wrapped<X, Other> = React.ComponentType<Output<X> & Other>

function withDownstreamProps<C extends Wrapped<any, any>>(
    WrappedComponent: C
) {
    return function<X, OtherProps>({foo, bar, baz, ...otherProps}: Input<X> & OtherProps) {
        return (
            <WrappedComponent
                {...otherProps}
                {...transform({foo, bar, baz})}
            />
        )
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM