React中的静态方法

Static methods in React

本文关键字:静态方法 React      更新时间:2023-10-31

我查看了React文档,并运行了静态方法。我想知道在什么样的情况下它可能有用,但想不出任何有用的。

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

defaultPropspropTypes是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) {
}