【问题标题】:Access statically defined variable in class definition [duplicate]在类定义中访问静态定义的变量[重复]
【发布时间】:2016-03-03 20:23:30
【问题描述】:

我有一堂课:

export default class Home extends React.Component {
    static store = createStore();

    constructor() {
        super();
        // This doesn't work
        console.log(this.store);
    }
}

并且我希望能够访问在类顶部定义的 store 变量,但是我不确定如何访问,我曾假设它是通过使用 this.store 但它未定义。

【问题讨论】:

  • this 是一个实例,而不是你的类。它没有store 属性?看看this question

标签: javascript ecmascript-6 ecmascript-next


【解决方案1】:

所以基本上你想在所有类实例之间共享变量?尝试将其传递给构造函数。像这样的:

class Home extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.store = props.store;

    console.log(this.store);
  }
}

你的初始化函数:

function init() {

  var props = {
    store: createStore()
  };

  ReactDOM.render(<Home {...props} />, document.getElementById('home1'));
  ReactDOM.render(<Home {...props} />, document.getElementById('home2'));
  ReactDOM.render(<Home {...props} />, document.getElementById('home3'));
}

和html:

<div id="home1"></div>
<div id="home2"></div>
<div id="home3"></div>

【讨论】:

    猜你喜欢
    • 2014-04-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-30
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多