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

javascript - Static methods in React - Stack Overflow

programmeradmin8浏览0评论

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 there a specific scenario in which static methods are useful when building components in React?

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 there a specific scenario in which static methods are useful when building components in React?

Share Improve this question edited Mar 31, 2016 at 13:09 AppRoyale 4031 gold badge5 silver badges21 bronze badges asked Mar 31, 2016 at 12:49 rameshramesh 2,4774 gold badges20 silver badges30 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 13

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)

  1. 暂无评论