【发布时间】:2019-10-03 01:14:59
【问题描述】:
我正在将一个 React 应用程序转换为使用大量函数式编程模式的 Typescript。这些模式中最重要的是将多个高阶组件组合在一起以返回增强组件的能力。我想要发生的事情是让 Typescript 在每个级别推断组件的类型,并以我传递的组件完成,以拥有其上方的所有 HOC 类型。
我已在 3.5.0 和最新版本的 Typescript 上尝试过此代码。代码方面,我尝试让泛型扩展我想要的类型 <T extends FooProps>,将 FC<T & BarProps> 传递给返回功能组件,并反转 HOC 的调用。
export const withFoo = <T>(Component: FC<T & FooProps>): FC<Omit<T, 'foo'>> => props => (
<Component {...props as T} foo="foo" />
)
export const withBar = <T>(Component: FC<T & BarProps>): FC<Omit<T, 'bar'>> => props => (
<Component {...props as T} bar="bar" />
)
export const EnhancedComponent = withFoo(
withBar(({ bar, foo }) => { // bar exists and foo does not exist on type 'PropsWithChildren<BarProps>'
console.log(bar) // types come through (bar: string)
console.log(foo) // types don't come through (foo: any) :(
return <div>woohoo</div>
}),
)
我希望这些类型在 HOC 的每个级别都通过。在上面的示例中,我想在我传递的功能组件中看到这一点:
export const EnhancedComponent = withFoo(
withBar(({ bar, foo }) => { // both exist on the component
console.log(bar) // bar: string
console.log(foo) // foo: string
return <div>woohoo</div>
}),
)
【问题讨论】:
-
个人意见:像这样堆叠 HOC 使用新的 hooks api 来共享有状态逻辑是 100% 过度杀伤
-
我同意钩子在大多数情况下都很好,但在这种情况下,我们希望根据父级的结果有条件地渲染其他 HOC。我们还希望能够渲染组件来处理错误和加载状态,而不是在渲染每个组件时处理它们,这就是我们使用 HOC 的原因。
标签: reactjs typescript function-composition higher-order-components