最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What is "static" doing in React? - Stack Overflow

programmeradmin5浏览0评论

I came across this code snippet on Codepen:

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  =  Handlebarspile( 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" ) );

Within the StarshipEnterprise class, they are using the word static in front of the object names. I've tried googling what these are and what they are doing, but all I'm getting is "The static keyword defines a static method for a class."

As a beginner, I have no idea what this means. Can anyone point me in the right direction on what these are doing or why I would need to use them?

I came across this code snippet on Codepen:

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" ) );

Within the StarshipEnterprise class, they are using the word static in front of the object names. I've tried googling what these are and what they are doing, but all I'm getting is "The static keyword defines a static method for a class."

As a beginner, I have no idea what this means. Can anyone point me in the right direction on what these are doing or why I would need to use them?

Share Improve this question asked Dec 15, 2018 at 19:53 RevircsRevircs 1,3523 gold badges14 silver badges25 bronze badges 2
  • 2 What makes you think its usage in React is different to general ES6 classes? – jonrsharpe Commented Dec 15, 2018 at 19:58
  • @jonrsharpe I've only ever used classes while learning React, so this is the first time I've seen static used in JavaScript at all – Revircs Commented Dec 15, 2018 at 21:46
Add a comment  | 

2 Answers 2

Reset to default 16

Static means a property that belongs to class only but not for it's instances.

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

Now we can use above static method through the class name:

       Triple.tripleFunc(3); //Valid

But not by creating it's instance:

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

Earlier in React we used to define propTypes and defaultProps outside the class by using following syntax :

    import React, {Component} from 'react';

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

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

Now we are defining it inside the class itself using static keyword here.

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

When we are importing SomeClass to another component then propTypes and defaultProps will be available in that component and can be accessed by using directly as:

    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
         }
       }

But we should not use it like this as when we are generating build it may remove, and we will be getting warning for the same.

The static keyword allows react to get the values of propTypes and defaultProps, without initializing your component.

Refer to the MDN documentation

The static keyword defines a static method for a class. Static methods aren't called on instances of the class. Instead, they're called on the class itself. These are often utility functions, such as functions to create or clone objects.M

发布评论

评论列表(0)

  1. 暂无评论