我有一个像这样的 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 的组件上使用它时,如下所示:
组件/产品.tsx
interface Props {
globalSettings: {
...
};
products: {
...
}[];
}
const Products: React.FunctionComponent<Props> = ({
globalSettings,
products,
}) => (
...
);
export default withGlobalSettings(Products);
在这种情况下, typescript 提示:
Property 'products' is missing in type 'PropsWithChildren' but required in type 'Props'.
我相信这是因为我没有正确设置 HOC 来传递除 prop 内生成的 globalSettings
以外的 prop。这是如何通过 typescript 中的功能组件 HOC 来实现的?
最佳答案
你需要这样的东西:
const wrapper = <T extends Props>(Component: React.ComponentType<T>) => (ownProps: Omit<T, keyof Props>) => {
const globalSettings = { test: 2 };
const props = { globalSettings, ...ownProps };
return <Component {...props as T} />;
};
你会这样使用它:
const NewProduct = wrapper(Product);
<NewProduct products={...} />
关于javascript - FunctionComponent HOC 的正确类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60026851/