故知
Web1.0
Web2.0
用 - Vue
学 - React
JSX
JSX
<div className='ui items'>
<p>
Hello, friend! I am a basic React component.
</p>
</div>
React.createElement('div', {className: 'ui items'},
React.createElement('p', null, 'Hello, friend! I am a basic React component.')
)
JSX之道 —— 语法糖
ES6 —— 面向未来的JS
Const & Let
const ProductList = React.createClass({ render: function () {
return (
<div className='ui items'>
Hello, friend! I am a basic React component.
</div>
);
},
});
let hello = "hello react";
块级作用域
ES6 —— 面向未来的JS
import & class
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
class Timer extends React.Component {
...
}
模块化
ES6 —— 面向未来的JS
Function Literal 箭头函数
const timestamps = messages.map(function(m) { return m.timestamp });
const timestamps = messages.map(m => m.timestamp);
Bable
<head>
<script src="vendor/babel-core-5.8.25.js"></script>
<body>
<script type="text/babel" src="./app-complete.js"></script>
</body>
</head>
Component
可复用的组件
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
Component - Props
描述组件的不可变属性
class MyTitle extends React.Component {
render() {
return <h1 style={{color: this.props.color}}>
Hello {this.props.message}
</h1>;
}
};
ReactDOM.render(
<MyTitle color='red' message='world'/>,
document.getElementById('mountNode')
);
Component - State
Component - State
Virtual DOM
Component - LifeCycle
Thinking In React
函数式编程的优势
单向数据流
七步创建React应用
Step 1 -- 将应用分解为组件
七步创建React应用
Step 2 -- 创建静态版本的应用
class Timer extends React.Component {
render() {
...
}
}
export default Timer;
七步创建React应用
Step 3 -- 确定哪些部分是有状态的
七步创建React应用
Step 4 -- 确定状态应该属于哪个组件
七步创建React应用
Step 5 -- 硬编码初始化状态
class ToggleableTimerForm extends React.Component {
constructor(props) {
super(props);
this.state = {
"isOpen": false
};
}
render() {
if (this.state.isOpen) {
return (
<TimerForm />
);
} else {
return (
...
}
}
}
export default ToggleableTimerForm;
七步创建React应用
Step 6 -- 添加反向数据流
class ToggleableTimerForm extends React.Component {
constructor(props) {
super(props);
}
handleFormClose() {...}
handleFormSubmit(timer) {...}
render() {
if (this.state.isOpen) {
return (
<TimerForm
onFormSubmit={this.handleFormSubmit.bind(this)}
onFormClose={this.handleFormClose.bind(this)}/>
);
} else {
...
}
}
}
七步创建React应用
Step 7 -- 添加后端数据通信
Text
核心组件
单页应用(SPA)
Webpack -- 解析模块依赖图,打包生成bundle.js
var webpack = require('webpack');
module.exports = {
devtool: debug ? "inline-sourcemap" : null,
entry: "./js/scripts.js",
output: {
path: __dirname + "/js",
filename: "scripts.min.js"
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin()
],
};
收益
更好的用户体验
一种设计模式
Text
一种设计模式
Text
名称解释
Store, Reducer, Dispacher
执行流程
代码实例
聊天室应用
Redux之道
Redux之道
基础形态 -- 在页面中嵌入component.js
进化形态 -- 使用WebPack
究极形态 -- 前后端分离
方案
基础,基础,基础
React
React Router, Flux, Redux