【问题标题】:What is the correct way to type a React HOC?输入 React HOC 的正确方法是什么?
【发布时间】:2019-02-22 00:41:19
【问题描述】:

我试图弄清楚我是否正确输入了我的反应高阶组件。在大多数情况下,这可以正常工作,但是在将 React 引用应用于 HOC 实例时,我遇到了打字问题。下面是一个简化的重现:

import * as React from "react";

// Is returning a React.ComponentClass correct here?
function HOC(): (Component: React.ComponentType) => React.ComponentClass {
    return function(Component: React.ComponentType): React.ComponentClass {
        return class Bar extends React.Component {}
    }
}

class Foo extends React.Component<{},{}> {}
const Bar = HOC()(Foo);

class Test extends React.Component {
    private ref: React.RefObject<typeof Bar> = React.createRef<typeof Bar>();

    render(): any {
        return (
            <React.Fragment>
              <Bar
                ref={this.ref} // error here
              />
            </React.Fragment>
        );
    }
}

我也在这里捕获了这个问题:https://stackblitz.com/edit/react-ts-rtmfwr

我得到的错误是:

index.tsx:20:21 - error TS2322: Type 'RefObject<ComponentClass<{}, any>>' is not assignable to type 'Ref<Component<{}, any, any>>'.
  Type 'RefObject<ComponentClass<{}, any>>' is not assignable to type 'RefObject<Component<{}, any, any>>'.
    Type 'ComponentClass<{}, any>' is not assignable to type 'Component<{}, any, any>'.
      Property 'setState' is missing in type 'ComponentClass<{}, any>'.

【问题讨论】:

    标签: reactjs typescript types higher-order-functions higher-order-components


    【解决方案1】:

    这应该可行:

    import * as React from "react";
    
    // In a more realistic example, there would be a more interesting relationship
    // between the props types of the wrapped and resulting components.    
    function HOC(): <P>(Component: React.ComponentType<P>) => React.ComponentClass<{}> {
        return function<P>(Component: React.ComponentType<P>): React.ComponentClass<{}> {
            return class Bar extends React.Component<{}> {}
        }
    }
    
    class Foo extends React.Component<{x: string},{}> {}
    const Bar = HOC()(Foo);
    // Get the instance type corresponding to the `Bar` constructor function,
    // as you would have if you had just written `class Bar`.
    type Bar = InstanceType<typeof Bar>;
    
    class Test extends React.Component {
        private ref: React.RefObject<Bar> = React.createRef<Bar>();
    
        render(): any {
            return (
                <React.Fragment>
                  <Bar
                    ref={this.ref}
                  />
                </React.Fragment>
            );
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-07
      • 2020-04-26
      • 1970-01-01
      • 1970-01-01
      • 2021-01-07
      • 2019-12-13
      • 2020-08-31
      相关资源
      最近更新 更多