类的创建
声明类的关键词:class
Student.js
export default class Student {
constructor(name, age) {
this.name = name;
this.age = age;
}
getDesc() {
return "我是:" + this.name + " 今年:" + this.age;
}
}
使用类:
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import Student from "./Student";
export default class ClassComponent extends Component {
constructor(props) {
super(props);
this.stu = new Student("小王", 27);
}
render() {
return <View>
<Text>获取Student类的实例子:name:{this.stu.name}+" age:"+{this.stu.age}+"\ngetDesc"+{this.stu.getDesc()}</Text>
</View>;
}
}
类的继承:
MingStudent.js
import Student from "./Student";
export default class MingStudent extends Student {
constructor() {
super("小明", 24);
}
getDesc() {
return "重写 getDesc:" + super.getDesc();
}
}
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import Student from "./Student";
import MingStudent from "./MingStudent";
export default class ClassComponent extends Component {
constructor(props) {
super(props);
this.stu = new Student("小王", 27);
this.stu2 = new MingStudent();
}
render() {
return <View>
<Text>获取Student类的实例子:name:{this.stu.name}+" age:"+{this.stu.age}+"\ngetDesc"+{this.stu.getDesc()}</Text>
<Text>获取MingStudent类的实例子:name:{this.stu2.name}+"
age:"+{this.stu2.age}"\ngetDesc"+{this.stu2.getDesc()}</Text>
</View>;
}
}