【问题标题】:HoC for context consumer causing type error with child component上下文消费者的 HoC 导致子组件的类型错误
【发布时间】:2019-02-26 05:52:14
【问题描述】:

我遇到了一个问题,我尝试编写一个 HoC 以包装应该可以通过新注入的道具访问特定上下文的组件。

有一个与教程相关的Gist,基本上包含以下sn-p:

export function withAppContext<
    P extends { appContext?: AppContextInterface },
    R = Omit<P, 'appContext'>
>(
    Component: React.ComponentClass<P> | React.StatelessComponent<P>
): React.SFC<R> {
    return function BoundComponent(props: R) {
        return (
            <AppContextConsumer>
                {value => <Component {...props} appContext={value} />}
            </AppContextConsumer>
        );
    };
}

同样有another snippet here on SO,如下所示:

function withTheme<P extends ThemeAwareProps>(Component: React.ComponentType<P>) {
    return function ThemedComponent(props: Pick<P, Exclude<keyof P, keyof ThemeAwareProps>>) {
        return (
            <ThemeContext.Consumer>
                {(theme) => <Component {...props} theme={theme} />}
            </ThemeContext.Consumer>
        )
    }
}

它们几乎相同,并且显然工作过一次,但现在情况已不再如此。使用这两种变体时,consume 的 render prop 中的子组件 Component 带有以下错误消息的下划线:

Type '{ exploreContext: IExploreContextStore; }' is not assignable to type 'IntrinsicAttributes & P & { children?: ReactNode; }'.
    Property 'exploreContext' does not exist on type 'IntrinsicAttributes & P & { children?: ReactNode; }'.

我出现问题的示例代码如下:

type WithExploreContext = { exploreContext?: IExploreContextStore };

export function withExploreContext<P extends WithExploreContext>(ChildComponent: ComponentType<P>) {
    return function WrappedComponent(
        props: Pick<P, Exclude<keyof P, keyof WithExploreContext>>
    ) {
        return <Consumer>{(value) => <ChildComponent {...props} exploreContext={value} />}</Consumer>;
    };
}

我几乎不知道这些 sn-ps 有什么问题,以及为什么它们不再按预期工作。

【问题讨论】:

    标签: reactjs typescript higher-order-components


    【解决方案1】:

    仅将props 传播到子组件是不够的。它在使用{...props as P} 将其转换为P 后立即开始工作。

    从 3.2 开始,behaviour of the spread operator for generics has changed。显然,props 的类型会作为负面影响被删除,但您可以通过在传播回包装组件时使用 {...props as P} 将其转换回 P 来解决此问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-06
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      • 2019-10-23
      • 1970-01-01
      • 1970-01-01
      • 2013-10-07
      相关资源
      最近更新 更多