【发布时间】:2021-03-15 21:52:11
【问题描述】:
我编写了一个我无法正确输入的 HOC 函数(这是预期的,因为我是 TypeScript 初学者,甚至是类型初学者)。这是函数:
const withLayout = (LayoutComponent, layoutProps = {}) => (WrappedComponent) => {
return function WithLayout(props) {
return (
<LayoutComponent {...layoutProps}>
<WrappedComponent {...props} />
</LayoutComponent>
)
}
}
我是这样使用的:
interface LayoutProps { a: string, b: string }
interface IndexProps { c: string, d: string }
class Layout extends React.Component<LayoutProps> { }
class Index extends React.Component<IndexProps> { }
withLayout(Layout, { a: 'a', b: 'b' })(Index)
这是我尝试输入的内容:
const withLayout = <LP extends JSX.IntrinsicAttributes & { children?: React.ReactNode }>(
LayoutComponent: React.ComponentType<LP>,
layoutProps: LP = {}
) => <WP extends JSX.IntrinsicAttributes & { children?: React.ReactNode }>(
WrappedComponent: React.ComponentType<WP>
) => {
return function WithLayout(props: WP): JSX.Element {
return (
<LayoutComponent {...layoutProps}>
<WrappedComponent {...props} />
</LayoutComponent>
)
}
}
我有几个问题,正如您在TypeScript playground 中看到的那样。我意识到我应该允许 layoutProps 和 props 分别成为 LayoutComponent 和 WrappedComponent 道具的对象,但我真的无法弄清楚将它传达给 TypeScript 的正确方法。有什么建议吗?
【问题讨论】:
-
您不能将默认的空对象作为
layoutProps传递,因为它没有所需的道具。你的泛型基本上没有被推断出来,所以我不得不玩弄这个,看看发生了什么。
标签: reactjs typescript react-typescript