-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.html
104 lines (92 loc) · 3.47 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>React Event Function</title>
<style>
.box {
border: 1px solid blue;
margin: 10px;
padding: 10px;
}
</style>
</head>
<body>
<div id="root"></div>
<script src="../libs/react.min.js"></script>
<script src="../libs/react-dom.min.js"></script>
<script src="../libs/babel.min.js"></script>
<script type="text/jsx">
/**
* 在类组件中,为元素绑定事件时,事件函数内可能会用到组件的一些属性或者方法,那么此时 this 指向会出现问题。
* 目前可以使用以下三种解决办法:
* 1、使用箭头函数代替普通函数
* 2、使用 bind 函数绑定 this 指向
* 3、使用匿名函数的方式调用组件的属性或者方法
*/
class ClassComponent extends React.Component {
// 箭头函数
arrowFunction = () => {
console.log('使用箭头函数,this 指向:', this);
}
// bind 绑定 this
bindFunction() {
console.log('使用 bind 改变 this 指向:', this);
}
render() {
return (
<React.Fragment>
<h3>类组件</h3>
<div>
<button onClick={ this.arrowFunction }>箭头函数打印 this</button>
<br /><br />
<button onClick={ this.bindFunction.bind(this) }>bind 函数打印 this</button>
<br /><br />
<button onClick={() => console.log('匿名函数调用,this 指向:', this)}>匿名函数打印 this</button>
</div>
</React.Fragment>
);
}
}
/**
* 在函数组件中,是不存在组件的 this 实例的,因此绑定事件时,不需要有类组件中的顾虑
*/
const FunctionComponent = () => {
// 箭头函数
const arrowFunction = () => {
console.log('使用箭头函数');
}
// bind 绑定函数
const bindFunction = function() {
console.log('使用 bind 调用函数');
}
// 普通函数
const normalFunction = function() {
console.log('调用普通函数');
}
return (
<React.Fragment>
<h3>函数组件</h3>
<div>
<button onClick={ arrowFunction }>普通函数</button>
<br /><br />
<button onClick={ arrowFunction }>箭头函数</button>
<br /><br />
<button onClick={ bindFunction.bind(this) }>bind 函数</button>
<br /><br />
<button onClick={() => console.log('匿名函数调用')}>匿名函数</button>
</div>
</React.Fragment>
);
}
const App = () => (
<div>
<ClassComponent />
<FunctionComponent />
</div>
)
ReactDOM.render(<App />, root);
</script>
</body>
</html>