Static methods in React

后端 未结 1 1003
眼角桃花
眼角桃花 2021-02-19 16:07

I was looking through the React documentation and ran into the static method. I Was wondering in what sort of scenario it might be useful and couldn\'t think of any.

Is

相关标签:
1条回答
  • 2021-02-19 16:24

    defaultProps and propTypes are static members of React components, they do not change for every instance. See https://facebook.github.io/react/docs/reusable-components.html

    One example for static properties is to be able to track how many instances of an object were created (not React specific). Note that most of the time, static methods are a code smell if you are modifying state.

    var Contacts = React.createClass({
      statics: {
        instanceCount: 0
      },
      getInitialState: function() {
         Contacts.instanceCount++
         return {};
      },
      render: function() {
        return (<div > Hello {
          this.props.name
        } < /div>);
      }
    });
    console.log(Contacts.instanceCount) // 0
    ReactDOM.render( < Hello name = "World" / > ,
      document.getElementById('container')
    );
    console.log(Contacts.instanceCount) // 1
    

    Another example is a way to store constants.

    var Contacts = React.createClass({
      statics: {
        MAX_VALUE:100
      },
      render: function() {
        return (<div > Hello {
          this.props.name
        } < /div>);
      }
    });
    
    if (someValue > Contacts.MAX_VALUE) {
    
    }
    
    0 讨论(0)
提交回复
热议问题