通常在React Native中需要初始化一些变量的值,除了props,state,全局变量global之外还存在,静态变量和成员变量。
成员变量:虽然组件的成员变量可以再任何需要它的地方定义,但还是建议在构造函数中对它们进行定义,这样还可以保证成员变量有初始值。
export default class Helloword extends Component{
constructor(props){
super(props);
this.name = "王思聪";//成员变量
this.age = 18;//成员变量
this.state = {text:''};
}
//render...
}
静态变量
export default class Helloword extends Component{
static staticObject = "沈腾";//定义类的静态成员变量
constructor(props){
super(props);
this.name = "王思聪";
this.age = 18;
this.state = {text:''};
}
//render...
}
静态函数
export default class Helloword extends Component{
static staticObject = "沈腾";//定义类的静态成员变量
static staticMethod(){//定义类的静态成员函数
console.log('于谦');
}
constructor(props){
super(props);
this.name = "王思聪";
this.age = 18;
this.state = {text:''};
}
//render...
}
注意访问静态变量或静态函数,直接以“类名.变量名(函数名)”的方式访问。不能以“this.变量名(函数名)”的方式访问。
HelloWorld.staticObject = "孙燕姿";
HelloWorld.staticMethod();