React_配置环境、ES6语法

配置 react 环境

React 官网

安装Git Bash(仅限使用 Windows 的同学,使用 Mac 和 Linux 的同学无需安装)

安装地址

安装Nodejs

安装地址 `

安装create-react-app

打开Git Bash,执行:

1
npm i -g create-react-app

安装VSCode的插件

  • Simple React Snippets
  • Prettier - Code formatter

创建React App

在目标目录下打开Git Bash,在终端中执行:

1
2
3
4
create-react-app react-app  # 可以替换为其他app名称

cd react-app
npm start # 启动应用

JSX

React中的一种语言,会被Babel编译成标准 JavaScript。

ES6 语法

使用bind()函数绑定this取值

在 JavaScript 中,函数里的this指向的是执行时的调用者,而非定义时所在的对象。

例如:

1
2
3
4
5
6
7
8
9
10
11
const person = {
name: "yxc",
talk: function () {
console.log(this);
},
};

person.talk();

const talk = person.talk;
talk();

运行结果:

1
2
{name: 'yxc', talk: ƒ}
Window

bind()函数,可以绑定this的取值。例如:

1
const talk = person.talk.bind(person);

箭头函数的简写方式

1
2
3
const f = (x) => {
return x * x;
};

可以简写为:

1
const f = (x) => x * x;

箭头函数不重新绑定this的取值

例如:

1
2
3
4
5
6
7
8
9
const person = {
talk: function () {
setTimeout(function () {
console.log(this);
}, 1000);
},
};

person.talk(); // 输出Window
1
2
3
4
5
6
7
8
9
const person = {
talk: function () {
setTimeout(() => {
console.log(this);
}, 1000);
},
};

person.talk(); // 输出 {talk: f}

对象的解构

例如:

1
2
3
4
5
6
7
const person = {
name: "yxc",
age: 18,
height: 180,
};

const { name: nm, age } = person; // nm是name的别名

数组和对象的展开

例如:

1
2
3
4
5
6
let a = [1, 2, 3];
let b = [...a]; // b是a的复制
let c = [...a, 4, 5, 6];
const a = { name: "yxc" };
const b = { age: 18 };
const c = { ...a, ...b, height: 180 };

Named 与 Default exports

  • Named Export:可以 export 多个,import 的时候需要加大括号,名称需要匹配
  • Default Export:最多 export 一个,import 的时候不需要加大括号,可以直接定义别名