React中的“静态”功能是什么?

时间:2018-12-15 19:53:22

标签: javascript reactjs

我在Codepen上遇到了this code snippet

const { Component, createElement, PropTypes } = React;

const source = `<p>Hello, my name is {{name}}. I work for {{employer}}. I have {{kids.length}} kids:</p> <ul>{{#kids}}<li>{{name}} is {{age}}</li>{{/kids}}</ul>`;

const template  =  Handlebars.compile( source );

class StarshipEnterprise extends Component {

    static propTypes = {
        name: PropTypes.string,
        employer: PropTypes.string,
        kids: PropTypes.arrayOf( PropTypes.object ),
    };

    static defaultProps = {
        name: "Data",
        employer: "United Federation of Planets",
        kids: [
            { 
                name: "Lal",
                age: "2"
            },
        ]
    };

    render () {
        return <div className="container" dangerouslySetInnerHTML={{ __html: template( this.props ) }} />;
    }

}

ReactDOM.render( createElement( StarshipEnterprise ), document.getElementById( "app" ) );

在StarshipEnterprise类中,他们在对象名称前使用单词static。我尝试使用Google搜索这些是什么以及它们在做什么,但是我得到的只是"The static keyword defines a static method for a class."

作为一个初学者,我不知道这意味着什么。有人能为我指出这些做法的正确方向或为什么我需要使用它们吗?

2 个答案:

答案 0 :(得分:2)

static关键字允许在不初始化组件的情况下做出反应以获取propTypesdefaultProps的值。

请参阅MDN documentation

  

static关键字为类定义了静态方法。在类的实例上不调用静态方法。而是在类本身上调用它们。这些通常是实用程序功能,例如用于创建或克隆对象的功能。M

答案 1 :(得分:2)

静态表示仅属于类的属性,但不属于其实例。

    class Triple {
       let triplevar = 0;
       static tripleFunc(n) {
          if(n == 1) { return 1;}
          else { return n*3; }
       }
    }

现在我们可以通过类名使用上述静态方法:

       Triple.tripleFunc(3); //Valid

但不能通过创建实例来实现:

       let tp = new Triple();
       tp.tripleFunc(6); //Not-Valid

在React的早期,我们曾经使用以下语法在类外定义propTypes和defaultProps:

    import React, {Component} from 'react';

    class SomeClass extends Component {
      constructor(props){
        super(props)
      }
    }

    SomeClass.proptypes = {};
    SomeClass.defaultProps = {};

现在我们在这里使用static关键字在类内部定义它。

    class SomeClass extends Component {
      constructor(props){
        super(props)
      }
      static propTypes = {};
      static defaultProps = {};
    }

当我们将SomeClass导入到另一个组件时,propTypes和defaultProps将在该组件中可用,并且可以通过直接用作以下内容来访问:

    class ChildClass extends SomeClass {
         constructor(props) {
            super(props);
            this.instanceSomeClass = new SomeClass();
            console.log(this.instanceSomeClass.propTypes);  // Will get undefined here
            console.log(SomeClass.propTypes) // it will be fine
         }
       }

但是我们不应该像这样使用它,因为当我们生成它时可能会删除它,并且我们将对此发出警告。