javascript - 如何将常量放入 React 组件中,并包装在 recompose 中

标签 javascript reactjs static

如何编写可以设置 this.state.status 的组件特定常量 STATUS?我认为问题在于 this 上下文。如果 this.STATUS 被硬编码在字符串中,它就可以工作。

import { compose } from 'recompose';
import React, { Component } from 'react';

class TestComponent extends Component {
    static propTypes = {};

    // can you put the STATUS constant on the component?
    static STATUS = {
        SENT: 'SENT',
        ERROR: 'ERROR',
    };

    state = { status: null };

    // functions cannot use this.STATUS
    f = () => {
        this.setState({status: this.STATUS.SENT});
        // undefined is not an object (evaluating '_this.STATUS.SENT')
    }

    render() {
        const { msg } = this.statusMessage();
        return ();
    }

}

export default compose(
  withRouter,
  connect(() => ())
)(TestComponent);

最佳答案

因为 STATUSstatic property类,您必须按如下方式访问它:

this.constructor.STATUS.SENT

如果将其声明为实例的属性,则可以通过 this.status 访问它:

STATUS = {
  SENT: 'SENT',
  ERROR: 'ERROR',
};

或通过 getter :

get STATUS() {
  return {
    SENT: 'SENT',
    ERROR: 'ERROR'
  };
}

关于javascript - 如何将常量放入 React 组件中,并包装在 recompose 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51864624/

相关文章:

javascript - 如何限制对函数的调用?

javascript - 无法使用后退按钮到嵌套列表(最新版本)

javascript - 如何在 React JS 中使用 jQuery 插件 "fullPage.js"

javascript - 如何使用状态更新 React js 中的对象数组

c++ - 派生类中的静态方法可以调用 C++ 中的 protected 构造函数吗?

javascript - 如何使用谷歌应用程序脚本设置谷歌表单中项目的父级?

javascript - Jquery在输入字段中输入美国手机号码时自动生成连字符

javascript - 如何在 reactjs 中的单击事件上设置状态和 Prop

c++ 带有静态变量的静态函数的奇怪行为

javascript - 使用 Flask 从目录中获取 leaflet.js 和 leaflet.css 时,传单 map 未出现