【问题标题】:How to use withRouter() with a generic component如何将 withRouter() 与通用组件一起使用
【发布时间】:2020-09-04 03:34:27
【问题描述】:

我有一个这样的组件:

function GenericComponent<T>(props: RouteComponentProps) {
    ...
}

export default withRouter(GenericComponent)

当尝试将它与&lt;GenericComponent&lt;SomeModel&gt; /&gt; 一起使用时,我收到以下错误:

预期的类型参数为 0,但得到了 1。

如何将T 传递给 withRouter?

【问题讨论】:

    标签: reactjs typescript react-router


    【解决方案1】:

    通常你不能那样做,我认为你可以让一个函数作为工厂工作,使用泛型 T 然后返回具有该类型的组件,如下所示:

    function GenericComponent<T>(props: RouteComponentProps<T>) {
      // ...
    }
    
    export function factory<T>() {
      return withRouter((props: RouteComponentProps<T>) => (
        <GenericComponent<T> {...props} />
      ));
    }
    
    // Usage
    function App() {
      const FooWithId = factory<{ id: string }>();
    
      return (
        <FooWithId />
      )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-07
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 2017-01-26
      • 2021-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多