小编典典

React中的静态方法

reactjs

我在浏览React文档并遇到了静态方法。我想知道在哪种情况下它可能有用,却没有想到。

在React中构建组件时,有没有特定的场景静态方法有用?


阅读 971

收藏
2020-07-22

共1个答案

小编典典

defaultProps并且propTypes是React组件的静态成员,它们不会在每个实例中都更改。参见https://facebook.github.io/react/docs/reusable-
components.html

静态属性的一个示例是能够跟踪创建了多少个对象实例(不是特定于React的)。请注意,大多数情况下,如果要修改状态,则静态方法会产生代码味道。

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

另一个示例是一种存储常量的方法。

var Contacts = React.createClass({
  statics: {
    MAX_VALUE:100
  },
  render: function() {
    return (<div > Hello {
      this.props.name
    } < /div>);
  }
});

if (someValue > Contacts.MAX_VALUE) {

}
2020-07-22