【问题标题】:React-Native-Navigation get rid of constructor?React-Native-Navigation 摆脱构造函数?
【发布时间】:2019-11-23 23:16:18
【问题描述】:
在react-native-navigation(不是react-navigation)的例子中说
constructor(props) {
super(props);
Navigation.events().bindComponent(this);
this.state = {
text: 'nothing yet'
};
}
在这种情况下有什么办法可以摆脱构造函数?
【问题讨论】:
标签:
reactjs
react-native
react-native-navigation
【解决方案1】:
在您的构造函数中基本上发生了三件事 - 对超类构造函数的调用、对Navigation.events().bindComponent 的调用以及初始状态。
如果你没有构造函数,super 构造函数仍然会被调用,你可以将状态初始化移到外面,像这样:
state = {
text: 'nothing yet'
};
但是,当您的类的实例在没有构造函数的情况下创建时,没有好的方法可以调用Navigation.events().bindComponent。所以如果你需要调用这个函数,你需要一个构造函数。