博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
React在ES6中的用法
阅读量:4087 次
发布时间:2019-05-25

本文共 58821 字,大约阅读时间需要 196 分钟。

写在前面

http://jafeney.com/2016/04/22/2016-04-22-react-ES6/不管是多么不乐意待见这个不速之客,但ES6已经一点点渗透进了我的生活里,就连我最爱的React到React Native,默认都把ES6做为首选标准。这是FaceBook有计划、有声势地要把ES6推起来,请问还有谁有狗胆站住来堵着路不走。所以我毅然捧着阮一峰老师的《ES6标准入门》在一旁看了起来……那好,今天就谈谈如何把React用ES6愉快地跑起来。

入门级Demos

先来几个简单的demo体验一把。注意,例子里ES5的require请通过browserfiy或webpack来实现,如果你还不会用这两样东西,请出门后往前看。

“Hello,XXX”输出

ES5写法:

1     
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var React = require('react');     
var HelloMessage = React.createClass({
render: function() {
return (

Hello,{this.props.name}!

);
}
});
module.exports = React.createClass({
render: function() {
return (
);
}
});

ES6写法:

1     
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import React,{Component} from 'react';     
class HelloMessage extends Component{
constructor() {
super();
}
render(){
return

Hello {this.props.name}

;
}
}
class Output extends Component{
constructor() {
super();
}
render(){
return (
);
}
}
export default Output;

数组遍历显示

ES5写法:

1     
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var React = require('react');     
var RepeatArray = React.createClass({
render: function() {
var names = ['Alice', 'Emily', 'Kate'];
var arrs = [

Hello World

,

React is awesome

];
return (
{arr}
{
names.map(function (name) {return
Hello, {name}!
;});
}
);
}
});
module.exports = RepeatArray;

ES6写法:

1     
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import React,{Component} from 'react';     
class RepeatArray extends Component{
constructor() {
super();
}
render(){
var arr = [

Hello world!

,

React is awesome

,
];
var names = ['Alice', 'Emily', 'Kate'];
return (
{arr}
{
names.map((name) =>{return
Hello, {name}!
;} )
}
);
}
}
export default RepeatArray;

ol与li的实现

ES5写法:

1     
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var React = require('react');     
var RepeatLi = React.createClass({
render: function() {
return(
    {
    this.props.children.map(function(child) {
    return
  1. {child}
  2. ;
    });
    }
);
}
});
module.exports = React.createClass({
render: function() {
return (
hello
world
);
}
});

ES6写法:

1     
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import React,{Component} from 'react';     
class RepeatLi extends Component{
render(){
return (
    {
    this.props.children.map((child)=>{return
  1. {child}
  2. })
    }
);
}
}
class RepeatArray extends Component{
constructor() {
super();
}
render(){
return (
hello
world
);
}
}
export default RepeatArray;

Click事件

ES5写法:

1     
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var React = require('react');     
var MyComponent = React.createClass({
handleClick: function() {
React.findDOMNode(this.refs.myTextInput).focus();
},
render: function() {
return (
);
}
});
module.exports = React.createClass({
render: function() {
return (
);
}
});

ES6写法:

1     
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import React,{Component} from 'react';     
class FocusText extends Component{
handleClick(){
React.findDOMNode(this.refs.myText).focus();
}
render(){
return(
);
}
}
class RepeatArray extends Component{
constructor() {
super();
}
render(){
return (
);
}
}
export default RepeatArray;

State的用法,以toggel显示文字为例

ES5写法:

1     
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var React = require('react');     
var LikeButton = React.createClass({
getInitialState: function() {
return {liked: false};
},
handleClick: function(e) {
this.setState({liked: !this.state.liked});
},
render: function() {
var text = this.state.liked ? 'like' : 'haven\'t liked';
return (

You {text} this.Click to toggle.

);
}
});
module.exports = React.createClass({
render: function() {
return (
);
}
});

ES6写法:

1     
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import React,{Component} from 'react';     
class StateUse extends Component{
constructor(){
super();
this.state={
like:true
}
}
handleClick(){
this.setState({like:!this.state.like});
}
render(){
var text = this.state.like?'Like':"Unlike";
return(

You {text} this.Click the toggle;

);
}
}
class RepeatArray extends Component{
constructor() {
super();
}
render(){
return (
);
}
}
export default RepeatArray;

onChange事件,以及变量值的同步

ES5写法:

1     
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var React = require('react');     
var InputComponent = React.createClass({
getInitialState: function() {
return {value: 'Hello!'};
},
handleChange: function(e) {
this.setState({value: e.target.value})
},
render: function() {
var value = this.state.value;
return (

{value}

);
}
});
module.exports = React.createClass({
render: function() {
return (
)
}
});

ES6写法:

1     
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import React,{Component} from 'react';     
class AsyncText extends Component{
constructor(){
super();
this.state={
value:'Hello!'
}
}
handleChange(e){
this.setState({value:e.target.value});
}
render(){
var value= this.state.value;
return(

{value}

);
}
}
class RepeatArray extends Component{
constructor() {
super();
}
render(){
return (
);
}
}
export default RepeatArray;

定时任务事件的嵌入

ES5写法:

1     
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
var React = require('react');     
var Hello = React.createClass({
getInitState: function() {
return {
opacity: 1.0
};
},
componentDidMount: function() {
this.timer = setInterval (function() {
var opacity = this.state.opacity;
opacity -= .05;
if (opacity < 0.1) {
opacity = 1.0;
}
this.setState({
opacity: opacity
});
}.bind(this), 100);
},
render: function() {
return (
Hello {this.props.name}
);
}
});
module.exports = React.createClass({
render: function() {
return (
);
}
});

ES6写法:

1     
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import React,{Component} from 'react';     
class OpacityWord extends Component{
constructor(){
super();
this.state={
opacity:1.0
}
}
componentWillMount(){
let time = setInterval(()=>{
let opacity = this.state.opacity;
opacity -= 0.5;
if (opacity<0.1) {
opacity=1.0;
}
this.setState({opacity:opacity});
}.bind(this),100);
}
render(){
return (
Hello, {this.props.name}!
);
}
}
class RepeatArray extends Component{
constructor() {
super();
}
render(){
return (
);
}
}
export default RepeatArray;

从服务端获取数据

ES5写法:

1     
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
var React = require('react');     
var UserGist = React.createClass({
getInitState: function() {
return {
username: '',
lastGistUrl: ''
};
},
componentDidMount: function() {
$.get(this.props.source, function(result) {
var lastGist = result[0];
this.setState({
username: lastGist.owner.login,
lastGistUrl: lastGist.html_url
});
}.bind(this));
},
render: function() {
return (
{this.state.username}s last gist is
here .
);
}
});
module.exports = React.createClass({
render: function() {
return (
);
}
});

ES6写法:

1     
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import React,{Component} from 'react';     
class UserGist extends Component{
constructor(){
super();
this.state={
username:'',
lastGistUrl:''
}
}
componentWillMount(){
$.get(this.props.source, function(result) {
var lastGist = result[0];
//if (this.isMounted()) {
this.setState({
username: lastGist.owner.login,
lastGistUrl: lastGist.html_url
});
//}
}.bind(this));
}
render(){
return(
{this.state.username} ..
here
);
}
}
class RepeatArray extends Component{
constructor() {
super();
}
render(){
return (
);
}
}
export default RepeatArray;

React Native实战

写一个简单的页面,支持输入关键字然后以列表形式呈现github里搜索出来的结果。效果如下:



ES5写法:

1     
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
'use strict';     
var React = require('react-native');
var {
Image,
ListView,
TextInput,
AppRegistry,
Component,
StyleSheet,
Text,
View,
} = React;
var BASE_URL = "https://api.github.com/search/repositories?q=";
var customView = React.createClass({
getInitialState: function() {
return {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
};
},
render: function() {
if (this.state.dataSource.getRowCount() === 0) {
console.log('YES');
}
var content = this.state.dataSource.getRowCount() === 0 ?
Please enter a search term to see results.
:
;
return (
{content}
);
},
onSearchChange: function(event: Object) {
var searchTerm = event.nativeEvent.text.toLowerCase();
var queryURL = BASE_URL + encodeURIComponent(searchTerm);
fetch(queryURL)
.then((response) => response.json())
.then((responseData) => {
if (responseData.items) {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(responseData.items),
});
}
}).done();
},
renderRow: function(repo: Object) {
return (
{repo.name}
{repo.owner.login}
);
},
});
var styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#ffffff',
},
searchBarInput: {
marginTop: 30,
padding: 5,
fontSize: 15,
height: 30,
backgroundColor: '#EAEAEA',
},
row: {
alignItems: 'center',
backgroundColor: 'white',
flexDirection: 'row',
padding: 5,
},
cellBorder: {
backgroundColor: 'rgba(0,0,0,0.1)',
height: 1,
marginLeft: 4,
},
profPic: {
width: 50,
height: 50,
},
title: {
fontSize: 20,
marginBottom: 8,
fontWeight: 'bold',
},
subTitle: {
fontSize: 16,
marginBottom: 8,
},
textContainer: {
paddingLeft: 10,
},
blankText: {
padding: 10,
fontSize: 20,
}
});
AppRegistry.registerComponent('customView', () => customView);

ES6写法:

1     
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import React, {     
Image,
ListView,
TextInput,
AppRegistry,
Component,
StyleSheet,
Text,
View,
}
from 'react-native';
const BASE_URL = "https://api.github.com/search/repositories?q=";
class customView extends Component {
constructor() {
super();
}
state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
}
render() {
if (this.state.dataSource.getRowCount() === 0) {
console.log('YES');
}
var content = this.state.dataSource.getRowCount() === 0 ?
Please enter a search term to see results.
:
;
return (
{content}
);
}
onSearchChange(event: Object) {
var searchTerm = event.nativeEvent.text.toLowerCase();
var queryURL = BASE_URL + encodeURIComponent(searchTerm);
fetch(queryURL)
.then((response) => response.json())
.then((responseData) => {
if (responseData.items) {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(responseData.items),
});
}
}).done();
}
renderRow(repo: Object) {
return (
{repo.name}
{repo.owner.login}
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#ffffff',
},
searchBarInput: {
marginTop: 30,
padding: 5,
fontSize: 15,
height: 30,
backgroundColor: '#EAEAEA',
},
row: {
alignItems: 'center',
backgroundColor: 'white',
flexDirection: 'row',
padding: 5,
},
cellBorder: {
backgroundColor: 'rgba(0,0,0,0.1)',
height: 1,
marginLeft: 4,
},
profPic: {
width: 50,
height: 50,
},
title: {
fontSize: 20,
marginBottom: 8,
fontWeight: 'bold',
},
subTitle: {
fontSize: 16,
marginBottom: 8,
},
textContainer: {
paddingLeft: 10,
},
blankText: {
padding: 10,
fontSize: 20,
}
});
AppRegistry.registerComponent('customView', () => customView);

参考 

你可能感兴趣的文章
Android Clean 架构
查看>>
Android 音视频学习资源汇总
查看>>
我的 2018 年终总结
查看>>
JVM 中如何判断对象可以被回收
查看>>
JVM 内存结构
查看>>
JVM 中的内存溢出
查看>>
maven的使用
查看>>
SpringMVC配置
查看>>
Java反射机制:从对象获取类的所有方法信息
查看>>
Java反射机制:获取成员变量和构造函数的信息
查看>>
Java反射机制:方法反射的基本操作
查看>>
Html和CSS的关系
查看>>
css样式分类
查看>>
Bootstrap:基本模板
查看>>
Bootstrap:常用的排版风格
查看>>
JavaScrit常用的简单交互
查看>>
web研发模式演变
查看>>
JavaScript:事件响应
查看>>
导入keras报错:module 'tensorflow.python.keras.backend' has no attribute 'get_graph'
查看>>
用anaconda安装tensorflow,keras
查看>>