【问题标题】:How do you access React statics within instance methods?你如何在实例方法中访问 React 静态变量?
【发布时间】:2020-03-26 20:29:07
【问题描述】:

我正在使用 React 16.13.0。我已经在我的组件中定义了这个静态块...

class FormContainer extends Component {
  statics: {
    DEFAULT_COUNTRY: 484;
  }

  constructor(props) {
    super(props);

    ...

  componentDidMount() {
    let initialCountries = [];
    let initialProvinces = [];
    // Get initial countries
    fetch('/countries/')
        .then(response => {
            return response.json();
        }).then(data => {
        initialCountries = data.map((country) => {
            return country
        });
        console.log("output ...");
        console.log(initialCountries);
        this.setState({
            countries: initialCountries,
        });
    });
    // Get initial provinces (states)
    console.log("val:" + this.DEFAULT_COUNTRY); 

我的问题是,如何引用该静态块?以上

console.log("val:" + this.DEFAULT_COUNTRY);

生产

undefined 

【问题讨论】:

  • 你期待某种特定的 React 特性吗?您似乎只是在 TypeScript 语法中定义公共属性的类型。
  • 我只是想知道如何访问静态变量的值。如果它与 React 无关,那就更好了。
  • 不过,这 不是 静态变量,因此是我的问题。我不确定你从哪里知道statics: {...} 是你想要的东西 - 你能分享一下吗?
  • 试试public static DEFAULT_COUNTRY = 484;
  • 感谢@johnannchopin,我可能应该提到这是一个 .jsx 文件。也许出于这个原因,当我尝试您的建议时,我收到编译错误“解析错误:意外标记”,并且编译错误标记指向“静态”一词。

标签: reactjs static constants instance-methods


【解决方案1】:

混淆来自旧的React.createClass 函数,如果您的运行时不支持类作为 Javascript 功能,您将使用该函数。您将在 React.createClass 中传递一个对象,React 将为该组件创建一个类。在那里,该对象上的statics 属性就像一个具有该伪类的所有静态属性的对象:

// old
const MyComponent = React.createClass({
  statics: {
    DEFAULT_COUNTRY: 484
  },
  render: function() {}
})

这里没有真正的类,它只是对象中的一个对象,确实很容易与例如混淆。 Java中的静态块

使用 ES6 类(您正在使用)静态属性是这样声明的

class MyComponent extends React.Component {
  static DEFAULT_COUNTRY = 484
  static ANOTHER_STATIC_PROPERTY = 23

  render () {}
}

并且可以在任何地方以MyComponent.DEFAULT_COUNTRY 的身份访问

您很可能使用 Babel,在这种情况下,应该启用 babel-plugin-proposal-class-properties,因为并非所有浏览器都支持此功能。没有 Babel 的节点从版本 12 开始支持类属性

Javascript 本身没有静态 blocks,但您可以从外部从静态上下文修改类,例如

class MyComponent extends React.Component {
  static DEFAULT_COUNTRY = 484
  static ANOTHER_STATIC_PROPERTY = 23

  render () {}
}

MyComponent.HELLO = 'world'

【讨论】:

    【解决方案2】:

    让我们使用:

    static DEFAULT_COUNTRY = 484

    使用static,您可以将属性/方法分配给类函数本身,而不是其原型。 FormContainer.DEFAULT_COUNTRY中this的值就是类构造函数FormContainer本身。

    您可以在班级内以this.constructor.DEFAULT_COUNTRY 的身份访问它。在课堂内外作为FormContainer.DEFAULT_COUNTRY。 所以,console.log("val:" + this.constructor.DEFAULT_COUNTRY);

    考虑以下作为存储 DEFAULT_COUNTRY` 的选项:

    class FormContainer extends Component {
      constructor(props) {
        super(props);
        this.DEFAULT_COUNTRY = 484;
      }
      render(){
        console.log(this.DEFAULT_COUNTRY)
        ...
      }
    };
    

    class FormContainer extends Component {
       DEFAULT_COUNTRY = 484;
       render(){
         console.log(this.DEFAULT_COUNTRY)
         ...
       }
    };
    

    或者,这也是一种选择:

    class FormContainer extends Component {
      statics = {
        DEFAULT_COUNTRY: 484,
      };
      render(){
        console.log(this.statics.DEFAULT_COUNTRY)
         ...
      }
    };
    

    但在最后一个例子中,statics 不是关键字,而只是类字段的名称。希望这会对你有所帮助。

    【讨论】:

      【解决方案3】:

      其实声明有问题,你应该使用下面的代码:

      class FormContainer extends Component {
        statics = { // use equal sign not colon sign
          DEFAULT_COUNTRY: 484, // use comma here not semicolon
        };
      

      然后在FormContainer 类的任何地方,您都可以通过this.statics 访问,对于您的默认国家/地区,您可以通过this.statics.DEFAULT_COUNTRY 访问。

      通过使用冒号声明类的statics 变量,您将得到undefined

      提示:不要使用static 关键字。它为在类内部不可访问的类定义了一个静态变量。在 ReactJS 中,static 关键字通常用于声明类道具成员的prop types


      更新

      为了证明代码的正确性:查看 IDE 和浏览器

      如果您遇到错误,请显示您的代码,也许您在不相关的地方调用它。

      【讨论】:

      • 这只是创建名为statics 的字段,与静态字段无关。与静态字段的最大区别在于,每次创建类的新实例时都会创建此对象。与仅在程序启动时创建一次的静态字段相反。此外,静态变量可以通过 MyClass.variableName 类访问
      • 嗨@AmerllicA,这不起作用。当我尝试“this.statics.DEFAULT_COUNTRY”时,出现编译错误“TypeError: Cannot read property 'DEFAULT_COUNTRY' of undefined”。
      • 亲爱的@Max,Dave 想在类中使用变量,static 定义它的键就像你说的那样可以访问。但这里是 ReactJS 环境。这是真正的方式。
      • 亲爱的@Dave,请查看更新,我认为您仍然使用冒号: 进行声明,或者您使用了static 关键字。请像我的截图一样写。使用= 声明statics,不要在statics 之前使用static 关键字。
      猜你喜欢
      • 2016-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-13
      • 1970-01-01
      • 2015-07-22
      • 2012-06-29
      • 1970-01-01
      相关资源
      最近更新 更多