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

如何编写类方法React.Component的类型注释?

  •  0
  • axm__  · 技术社区  · 8 年前

    React.Component 的类方法。因此,我想提取类方法的类型注释,并将它们创建(和导出)为单独的类型。在下面的例子中 handleClick()

    export type Amount: number;
    interface State {
        amount: Amount;
    }
    
    class Example extends React.Component<{}, State> {
        handleClick(e: React.FormEvent<HTMLInputElement>) {
            // some code
        }
        render() {
            <AnotherComponent
                amount={this.state.amount}
                handleClick={this.state.handleClick}
            />
        }
    }
    

    它的类型注释应该提取到:

    export type HandleClickType = (e: React.FormEvent<HTMLInputElement>) => void;
    

    我想我可以很容易地把它放回去,比如:

    class Example extends React.Component<{}, State> {
        handleClick : HandleClickType (e) {}
    }
    

    我该怎么做?我要这样做的原因是,当我将函数作为props传递并且必须重新键入类型注释时,防止代码重复。

    1 回复  |  直到 8 年前
        1
  •  2
  •   Titian Cernicova-Dragomir    8 年前

    你可以这样做,但是函数将是一个字段而不是一个方法,有细微的区别。

    首先是解决方案。函数类型正常,但初始化字段的方式不正常:

    class Example extends React.Component<{}, State> {
        handleClick:HandleClickType = (e) => {
            this // is Example
        }
    
        handleClickFunction:HandleClickType = function(e) {
            this // this is any and might cause an error depending on compiler settings
        }
    }
    

    第一个字段初始化为箭头函数,因此捕获 this 从类上下文和访问 将按预期工作。第二个例子使用一个正则函数 这 any 也就是说 noImplcitThis 这 将被取消选中,因为它是any类型)

    我们可以通过使用显式注释或向函数类型添加额外的参数来帮助推断 这

    export type HandleClickType = (e: React.FormEvent<HTMLInputElement>) => void;
    export type HandleClickTypeWithThis<T> = ( this: T, e: React.FormEvent<HTMLInputElement>) => void;
    class Example extends React.Component<{}, State> {
      handleClickFunctionWithInfferedThis: HandleClickTypeWithThis<this> = function (e) {
        this // this is now example
      }
      handleClickFunctionWithExplcitThis: HandleClickType = function (this: Example, e) {
        this // this is now example
      }
    }
    

    我提到 function

    关于方法和函数域之间的细微差别。除了两个对象将使用不同的图标代码完成外,最大的区别是方法被分配一次并分配给原型,而使用字段闭包将被创建并分配给每个对象的实例。这将导致更多的内存使用,这在某些情况下可能很重要。但如果你需要抓住 不管怎样,这都无关紧要,因为你无论如何都会有一个新的结束。