代码之家  ›  专栏  ›  技术社区  ›  invariant

如何在typescript中接受react组件构造函数作为函数参数

  •  1
  • invariant  · 技术社区  · 7 年前
    import { Component} from "react";
    
    export class Test extends Component<{}, {}> {
          render() {
            return "Hello";
          }
        }
    
        function myFunction<P, S, C extends Component<P, S>>(c: C): void {
          console.log("ctor", c);
        }
    
        const s = myFunction(Test);
    

    错误:

    类型为“typeof Test”的参数不能分配给类型为的参数 '组件(<);{},{}>'。类型“typeof”中缺少属性“setState” 测试”。07:35:53-编译完成。监视文件更改。

    我需要实现原始react的所有成员吗 Component 使用super初始化。(..) ?

    1 回复  |  直到 7 年前
        1
  •  2
  •   CRice    7 年前

    您需要声明 C 作为对返回组件的可更新函数的扩展:

    import { Component} from "react";
    
    export class Test extends Component<{}, {}> {
        render() {
            return "Hello";
        }
    }
    
    function myFunction<P, S, C extends new () => Component<P, S>>(c: C): void {
        console.log("ctor", c);
    }
    
    const s = myFunction(Test);