【问题标题】:Correct types for FunctionComponent HOCFunctionComponent HOC 的正确类型
【发布时间】: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 谢谢,我确实看过那篇文章,使用的示例是类组件,没有钩子和不同的类型。
  • 关键是你需要在那里使用泛型,并返回一个带有&lt;Generic &amp; Props&gt;的组件

标签: javascript reactjs typescript


【解决方案1】:

你需要这样的东西:

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={...} />

【讨论】:

  • 这不需要传递一些道具作为 HOC 上的第二个参数,例如:export default withGlobalSettings(Products, { ...someProps });
  • 是的,包装好的产品组件需要从某个地方获取他自己的参数(因为它们是强制性的)。您打算如何将这些参数推送到产品组件?
  • 关于组件的使用如下:&lt;Products products={[...]} /&gt;
  • 查看我的编辑,现在部分 props 来自 HOC,部分来自您提供(类似于 react-redux connect hoc 的工作方式)
  • 我希望我能给这个超过 1 个赞!不能告诉你我今天在这上面浪费了多久。非常感谢!!
猜你喜欢
  • 1970-01-01
  • 2017-11-04
  • 2021-09-25
  • 1970-01-01
  • 2023-04-08
  • 2022-01-18
  • 2019-01-19
  • 2019-03-02
  • 2019-12-30
相关资源
最近更新 更多