gpt4 book ai didi

javascript - FunctionComponent HOC 的正确类型

转载 作者:行者123 更新时间:2023-12-01 00:11:52 27 4
gpt4 key购买 nike

我有一个像这样的 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com