【发布时间】:2019-05-30 05:09:08
【问题描述】:
我目前正在尝试重新组合到我的反应代码库中。因此,我试图让一些基本的东西正常工作,并且我得到了它的工作,但我不确定这是否是 recompose 的正确工作方式。
所以我有以下代码:
interface Value {
value: string
}
interface Loading {
loading: boolean
}
const TestComponent = (props: Value) => <div>Value: {props.value}</div>
const LoadingComponent = () => <div>Loading ...</div>
所以我有一个 TestComponent,它应该显示道具中提供的值,另外我还有一个 LoadingComponent,它应该在设置加载道具时显示。
所以我使用了recompose的branch函数
const withLoading = branch<Loading>(
({loading}) => loading,
renderComponent(LoadingComponent)
)
现在,当我在 任何没有道具的组件上使用 withLoading时,我可以在它们上设置加载道具。
const EnhancedCompWithLoading = withLoading(SomeCompWithoutProps)
render() {
return <EnhancedCompWithLoading loading={this.state.loading} />
}
这对我来说很好用,真正的问题是在尝试将其与带有道具的组件一起使用时开始。当我这样尝试时:
const TestWithLoading = withLoading(TestComponent)
render() {
return <TestWithLoading value="testVal" loading={this.state.loading} />
}
我收到错误消息TS2339: Property 'value' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<Loading, any, any>>
& Readonly<{ children?: ReactNode; }> & Readonly<Loading>'.
所以我查看了@types/recompose 中的类型定义。 branch<TOutter> 返回 ComponentEnhancer<any,TOutter>。据我所知,我希望能够提供any 组件,而<TOutter> 泛型就是这样,生成的组件知道测试功能所需的道具。这也可以在没有额外道具的情况下工作。
但是 ComponentEnhancer 的 TypeDefinition 看起来像这样(重构 0.30.2):
interface ComponentEnhancer<TInner, TOutter> {
(component: Component<TInner>): ComponentClass<TOutter>
}
所以,我从之前的branch 函数收到的ComponentEnhancer<any, Loading> 将返回一个ComponentClass<Loading>。但是,我提供给 ComponentEnhancer 的组件的 <TInner> 将被丢弃,并且我无法在增强组件中使用我的 Value 道具。
所以我的问题是,我做错了吗,有没有更好的方法来实现这一点(使用重组)。或者它只是 TypeDeclaration 中的一个错误,因为将 ComponentEnhancer 的返回更改为 ComponentClass<TOutter & TInner> 为我解决了整个问题。
对此有什么想法吗?
【问题讨论】:
标签: javascript reactjs typescript recompose