typescript 在构造函数或声明中初始化变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39619844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:51:41  来源:igfitidea点击:

Initialize variables in constructor or in declaration

reactjstypescript

提问by Lambert

When using ReactJS with TypeScript, is it better to initialize class variables in the constructor or when the class variable is being declared? It works fine either way and the transpiled javascript looks the same either way.

将 ReactJS 与 TypeScript 一起使用时,是在构造函数中初始化类变量还是在声明类变量时更好?无论哪种方式它都可以正常工作,并且转换后的 javascript 看起来都一样。

export class MyClass extends React.Component<iProps, {}> {
      private myName: string = "Hello";

      constructor(props: iProps) {
         super(props);

         this.myName= "Hello";
      }
}

采纳答案by Nitzan Tomer

It's exactly the same, for example:

完全一样,例如:

class MyClass1 {
      private myName: string = "Hello";
}

Compiles to:

编译为:

var MyClass1 = (function () {
    function MyClass1() {
        this.myName = "Hello";
    }
    return MyClass1;
}());

And:

和:

class MyClass2 {
      private myName: string;

      constructor() {
         this.myName = "Hello";
      }
}

Compiles to:

编译为:

var MyClass2 = (function () {
    function MyClass2() {
        this.myName = "Hello";
    }
    return MyClass2;
}());

(code in playground)

操场上的代码

As you can see the compiled versions are identical (except for the class names).
So you can use which one you find more elegant.

如您所见,编译版本是相同的(类名除外)。
所以你可以使用你觉得更优雅的那个。

As for react, you can use the props which are passed to the constructor.
When using es6 style classes with react components then your initial state is assigned in the constructor and not using the getInitialStatemethod.
If your initial state is a function of the props then you'll need to use those in the constructor.

至于反应,您可以使用传递给构造函数的道具。
当将 es6 样式类与 react 组件一起使用时,您的初始状态将在构造函数中分配,而不是使用该getInitialState方法。
如果您的初始状态是 props 的函数,那么您需要在构造函数中使用它们。