在React Native中声明全局类变量

时间:2017-06-28 17:57:57

标签: reactjs react-native

在我的类构造函数中,我从导航道具中声明了一些常量。但是,我无法在课程的其他部分访问这些常量。我可以制作更多变量this.data = datathis.key = key ......但这可能是多余的。

  constructor(props){
    super(props);
    const {navigate} = this.props.navigation;
    const { name, who, what, time, date, where, key } = this.props.navigation.state.params;
    this.date = date;
    this.key = key;
    this.state = {
      changed: false,
      saving: false,
      cancel: false,
      curTitle: name,
      curWho: who,
      curTime: time,
      curDate: date,
      curDescription: what,
      curWhere: where
    }
    console.ignoredYellowBox = ['Setting a timer'];
    console.log(this.date + " " + this.key);
  }   

1 个答案:

答案 0 :(得分:2)

vars正确绑定。

您可能必须绑定要访问这些变量的函数:

....
constructor(props){
  super(props);
  this.something = 'foo';
  this.doSomething = this.doSomething.bind(this);
}
doSomething() {
  console.log(this.something); // will show 'foo'
}
...

希望这有帮助。