【发布时间】:2020-02-03 01:14:34
【问题描述】:
我有一个这样的 HOC:
utils/withGlobalSettings.tsx
interface Props {
globalSettings: {
...
};
}
export default (Component: React.ComponentType<Props>) => () => {
const locale = useContext(localeContext);
const { data } = useQuery(dataGlobalSettingsCollection);
return <Component globalSettings={globalSettings} />;
};
我在几个简单的组件上使用了它,效果很好。问题是当我在一个期望它自己的 props 的组件上使用它时,就像这样:
components/Products.tsx
interface Props {
globalSettings: {
...
};
products: {
...
}[];
}
const Products: React.FunctionComponent<Props> = ({
globalSettings,
products,
}) => (
...
);
export default withGlobalSettings(Products);
在这种情况下,打字稿会抱怨:
“PropsWithChildren”类型中缺少属性“products”,但 在“道具”类型中是必需的。
我相信这是因为我没有正确设置 HOC 以通过除 globalSettings 在道具内部生成的道具之外的道具。 typescript 中的功能组件 HOC 是如何实现的?
【问题讨论】:
-
什么是全局设置?错误抛出的地方在哪里? - 你可以添加评论吗?
-
withGlobalSettings是 HOC(我的第一个代码 sn-p,我将其标记为utils/withGlobalSettings.tsx。使用 HOC 时会引发错误,特别是在单个参数Products上。跨度> -
@ritaj 谢谢,我确实看过那篇文章,使用的示例是类组件,没有钩子和不同的类型。
-
关键是你需要在那里使用泛型,并返回一个带有
<Generic & Props>的组件
标签: javascript reactjs typescript