javascript - FunctionComponent HOC 的正确类型

标签 javascript reactjs typescript

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

相关文章:

javascript - 使用 jQuery 根据输入值为子元素添加类

javascript - 在模板中访问 "this"

javascript - JS - 在其中一个对象上添加新属性和值

reactjs - 对象作为 React 子对象无效(发现 : object with keys {})

reactjs - 无法使用 React 将电子商务数据发送到 Google Analytics

javascript - TypeError : navigator. currentLang 不是函数

JavaScript 正则表达式在 Firefox 中失败

reactjs - 从react-router-dom url中删除哈希

typescript 错误 : Property defined as private on type Class is defined as public on type Interface

angular - TypeScript:不允许多个构造函数实现