一. ES6的class
虽然目前React开发模式中更加流行hooks,但是依然有很多的项目依然是使用类组件(包括AntDesign库中);
但是有很多的同学对ES6中的类不太熟悉,所以这里我还是补充一下;
1.1. 类的定义
在ES6之前,我们通过function来定义类,但是这种模式一直被很多从其他编程语言(比如Java、C++、OC等等)转到JavaScript的人所不适应。
原因是,大多数面向对象的语言,都是使用class关键字来定义类的。
而JavaScript也从ES6开始引入了class关键字,用于定义一个类。
ES6之前定义一个Person类:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.running = function() {
console.log(this.name + this.age + "running");
}
var p = new Person("why", 18);
p.running();
转换成ES6中的类如何定义呢?
- 类中有一个constructor构造方法,当我们通过new关键字调用时,就会默认执行这个构造方法
- 构造方法中可以给当前对象添加属性
- 类中也可以定义其他方法,这些方法会被放到Person类的prototype上
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
running() {
console.log(this.name + this.age + "running");
}
}
const p = new Person("why", 18);
p.running();
另外,属性也可以直接定义在类中:
- height和address是直接定义在类中
class Person {
height = 1.88;
address = "北京市";
constructor(name, age) {
this.name = name;
this.age = age;
}
studying() {
console.log(this.name + this.age + "studying");
}
}
1.2. 类的继承
继承是面向对象的一大特性,可以减少我们重复代码的编写,方便公共内容的抽取(也是很多面向对象语言中,多态的前提)。
ES6中增加了extends关键字来作为类的继承。
我们先写两个类没有继承的情况下,它们存在的重复代码:
- Person类和Student类
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
running() {
console.log(this.name, this.age, "running");
}
}
class Student {
constructor(name, age, sno, score) {
this.name = name;
this.age = age;
this.sno = sno;
this.score = score;
}
running() {
console.log(this.name, this.age, "running");
}
studying() {
console.log(this.name, this.age, this.sno, this.score, "studing");
}
}
我们可以使用继承来简化代码:
- 注意:在constructor中,子类必须通过super来调用父类的构造方法,对父类进行初始化,否则会报错。
class Student1 extends Person {
constructor(name, age, sno, score) {
super(name, age);
this.sno = sno;
this.score = score;
}
studying() {
console.log(this.name, this.age, this.sno, this.score, "studing");
}
}
const stu1 = new Student1("why", 18, 110, 100);
stu1.studying();
二. 案例练习
2.1. 列表展示
真实开发中,我们的数据通常会从服务器获取,比较常见的是获取一个列表数据,保存到一个数组中进行展示
- 比如现在有一个电影列表,我们如何通过React进行展示呢?
我们还是通过一个组件来完成:
class App extends React.Component {
constructor(props) {
super(props);