【问题标题】:React statics with ES6 classes使用 ES6 类反应静态
【发布时间】:2015-06-08 14:22:51
【问题描述】:

静态对象是否适用于 React 中的 ES6 类?

class SomeComponent extends React.Component {

  render() {
    // ...
  }

}

React.statics = {
  someMethod: function() {
    //...
  }
};

当我执行SomeComponent.someMethod() 时,上面的内容给了我未定义的方法someMethod

【问题讨论】:

    标签: reactjs ecmascript-6


    【解决方案1】:

    statics 仅适用于 React.createClass。只需将该方法声明为静态类方法:

    class SomeComponent extends React.Component {
    
      static someMethod() {
        //...
      }
    
      render() {
        // ...
      }
    
    }
    

    关于

    React.statics = { ... }
    

    您实际上是在 React 对象上创建 statics 属性。该属性不会神奇地扩展您的组件。

    【讨论】:

    • 请注意,babel 和 jsx 工具支持静态属性(例如 static propTypes = {...});但只是一个 ES7 提案。静态方法是 ES6。
    • 这样做我总是得到Cannot read property '_currentElement' of null 错误,而没有静态修饰符的相同方法可以正常工作。我没有在我的方法中使用任何类变量...
    【解决方案2】:

    虽然statics 仅适用于React.createClass,但您仍然可以用 ES6 表示法编写静态方法。如果你使用的是 ES7,那么你也可以写静态属性。

    您可以通过这种方式在 ES6+ 类中编写静态:

    class Component extends React.Component {
        static propTypes = {
        ...
        }
    
        static someMethod(){
        }
    }
    

    或者像这样在课外:

    class Component extends React.Component {
       ....
    }
    
    Component.propTypes = {...}
    Component.someMethod = function(){....}
    

    如果你想像前者那样写,那么你必须在 Babel 上设置stage: 0(因为它是实验性的)。

    【讨论】:

    • 请注意 propTypes = … 不是 ES6 表示法。
    • 你是对的,这似乎是 ES7 属性初始化符号。 facebook.github.io/react/blog/2015/01/27/…
    • 要使用 ES7,你必须 npm install babel-preset-stage-0 然后将 "stage-0" 添加到 .babelrc 中,如下所示:{"presets": ["es2015", "react", "stage-0"]}
    【解决方案3】:

    无需实例化组件即可访问静态数据。通常它们没有那么有用,但有一些特殊情况。例如,当您离开当前页面时执行 ACTION PERFORM 进入路由,然后通过静态方法,您可以保持/询问用户是否真的想离开页面。 例如:

    exampleComponent= React.createClass({
    statics:{
            willTransitionFrom: function(transition,component){
                // check any state here or value Aasked the user.
            }
        }
    });
    

    它公开 willTransitionTo 和 willTransitionFrom 生命周期方法。两者都特别有用,因为您可以在实例化组件之前取消转换。

    【讨论】:

      【解决方案4】:

      停下来。只需声明一个类而不扩展 React.Component 即可。

      class YourStaticClass {
      
         static YourMethod(){
      
         }
      
      }
      export default YourStaticClass;
      

      在其他类中, 你可以简单地导入你的类并触发函数

      import YourStaticClass from "whatever";
      
      ...
      YourStaticClass.YourMethod();
      ...
      

      【讨论】:

        【解决方案5】:

        statics 仅适用于 React 组件,check docs。

        【讨论】:

        • OP没有react组件吗?
        • 这正是您的答案。什么是 OP?
        • "OP" 指问题或写问题的人。也许你只是措辞有点奇怪,因为这绝对是一个 React 组件。它不是用React.createClass 创建的。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-06-03
        • 2018-12-25
        • 2017-10-20
        • 2018-09-11
        • 2015-09-15
        • 1970-01-01
        相关资源
        最近更新 更多