【发布时间】: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