如何编写可以设置 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);
最佳答案
因为 STATUS
是 static 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/