安装 React 的学习环境

1
2
3
4
5
6
7
8
9
10
11
12
13
// 安装创建 react 项目的工具
npm install -g create-react-app

// 创建一个项目
➜ Project create-react-app jiajia-react
Creating a new React app in /Users/myCode/Project/jiajia-react.

Installing packages. This might take a couple minutes.
Installing react, react-dom, and react-scripts...

// 启动项目
cd jiajia-react
npm start

目录结构介绍

  • node_modules 存放 npm 包的目录。
  • public 存放静态资源,提供外部访问。
  • src 存放源代码。

业务调用顺序

src/index.js 中有如下代码,程序首先导入了 React 和 ReactDom 模块,并导入了一个当前目录下的 App 模块。随后在代码中使用 ReactDOM.render 将 App 模块渲染到了界面上。这个 App 在 React 中称为组件(component)。而这个组件渲染到什么位置则是第二个参数 document.getElementById(‘root’) 决定的,它从 index.html 中获取到了 root 节点,并将 App 插入到 root 节点下。

1
2
3
4
5
6
7
8
9
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';

ReactDOM.render(
<App />,
document.getElementById('root')
);

而 App 组件中首先导入了 React 的 Component,并创建了一个 App 的类,继承与 React 的 Component。里面实现了 render 函数,该函数仅返回了一些 html 代码,用于界面上显示。值得注意的是,由于 class 是 JavaScript 的关键字,所以在给 div 添加样式的时候,要将 class 修改为 className。这里的代码是 jsx 语法。最终将实现好的 App 通过 ES6 的 export 语法将这个模块导出提供外部使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}

export default App;

编译生产环境的项目

1
2
3
4
5
6
7
8
// 编译项目,会在项目目录下生成一个 build 的文件夹。
npm run build

// 安装 pushstate-server 用于将已经编译好的项目部署
npm install -g pushstate-server
// 将编译项目运行在本地查看效果
pushstate-server build
// Listening on port 9000 (http://0.0.0.0:9000)

执行以上命令后,会产生一个编译后的生产环境的代码。浏览器访问 http://0.0.0.0:9000 后就能看到编译后的测试项目了。