|
@@ -195,6 +195,58 @@ ReactDOM.createRoot(document.querySelector('#root')).render(element);
|
|
|
);
|
|
|
```
|
|
|
|
|
|
+### 4.2 监听器中的this
|
|
|
+
|
|
|
+> 在React16之前,事件的监听器中this可能会被频繁使用。因此我们需要记住this的绑定值。
|
|
|
+>
|
|
|
+> 但是在React18之后,即推出Hook之后,开发者就可以绕过 JS 中难以理解的this指向。
|
|
|
+
|
|
|
+原生事件属性绑定的监听器中的this
|
|
|
+
|
|
|
+```html
|
|
|
+<button onclick="onClick1()">原生事件1</button>
|
|
|
+<button id="btn">原生事件2</button>
|
|
|
+<script type="text/babel">
|
|
|
+ function onClick1() {
|
|
|
+ console.log(this); // undefined
|
|
|
+ }
|
|
|
+
|
|
|
+ function onClick2() {
|
|
|
+ console.log(this); // button元素
|
|
|
+ }
|
|
|
+ document.getElementById('btn').onclick = onClick2;
|
|
|
+</script>
|
|
|
+```
|
|
|
+
|
|
|
+但是在React中 监听器的this 与HTML属性注册事件是一样的,即监听器中的this不会绑定任何事。
|
|
|
+
|
|
|
+```html
|
|
|
+<div id="root"></div>
|
|
|
+<script type="text/babel">
|
|
|
+function onClick() {
|
|
|
+ console.log(this);// undefined 不会绑定任何值
|
|
|
+}
|
|
|
+let element = <button onClick={onClick}>click me</button>;
|
|
|
+ReactDOM.createRoot(document.querySelector('#root')).render(element);
|
|
|
+</script>
|
|
|
+```
|
|
|
+
|
|
|
+如果这些监听器函数中的this需要有一个有效值:
|
|
|
+
|
|
|
+```html
|
|
|
+<div id="root"></div>
|
|
|
+<script type="text/babel">
|
|
|
+var obj = {name: 'big fat girl baby'};
|
|
|
+function onClick() {
|
|
|
+ console.log(this);// undefined 不会绑定任何值
|
|
|
+}
|
|
|
+let element = <button onClick={onClick.bind(obj)}>click me</button>;
|
|
|
+ReactDOM.createRoot(document.querySelector('#root')).render(element);
|
|
|
+</script>
|
|
|
+```
|
|
|
+
|
|
|
+### 4.3 给监听器传入额外参数
|
|
|
+
|
|
|
|
|
|
|
|
|
## 5. 组件
|