javascript - 类和反应组件中的 this 关键字行为(箭头函数与常规函数)
问题描述
我试图了解 this 关键字在与事件处理程序配对时在反应组件(箭头函数与常规函数)中的行为。
为此,我创建了两个示例,一个使用 HTML/vanilla JS,另一个使用 React。
HTML/VanillaJS
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button class="btn-arr">Log this Arr</button>
<button class="btn-reg">Log this Reg</button>
<script>
class App {
logThisArr = () => {
console.log('Arr : ', this);
};
logThisReg = function () {
console.log('Reg : ', this);
};
}
const app = new App();
const btnArr = document.querySelector('.btn-arr');
const btnReg = document.querySelector('.btn-reg');
btnArr.addEventListener('click', app.logThisArr); // Arr : App {logThisArr: ƒ, logThisReg: ƒ}
btnReg.addEventListener('click', app.logThisReg); // Reg : <button class="btn-reg">Log this Reg</button>
</script>
</body>
</html>
反应
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import registerServiceWorker from './registerServiceWorker';
class App extends Component {
logThisArr = () => {
console.log('arrow : ', this);
};
logThisReg = function() {
console.log('Reg : ', this);
};
render() {
return (
<div className="App">
<button onClick={this.logThisArr}>Log this Arr</button>
{/* Arr : App {props: {…}, context: {…}, refs: {…}, updater: {…}, logThisArr: ƒ, …}*/}
<button onClick={this.logThisReg}>Log this Reg</button>
{/*Reg : undefined */}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
为什么我在使用常规函数时没有得到相同的输出?在反应中,我得到“未定义”,而在 vanillaJS 中,我得到了按钮对象。
谢谢 !
解决方案
您不必处理this
. 但不要忘记绑定回调事件(关于事件的 React Doc)以始终拥有良好的参考
只需将其添加到App Component
constructor(props) {
super(props);
this.logThisArr = this.logThisArr.bind(this);
this.logThisReg = this.logThisReg.bind(this);
}
推荐阅读
- python - 具有多个 n 数的时间序列数据预测
- angular - ion-img 在旧版本的 ionic ~3.* 上无法正常工作
- java - 从 Spring Boot 自定义验证器返回不同的 HTTP 状态代码
- python - 在 Python 中使用版本号对元组列表进行排序
- python - 如何遍历数据框中的列并在每次迭代中打印每个值
- javascript - 我的引导图像轮播有点像移动设备上的每张幻灯片滑动两次
- random - 保持变量之间的关系
- python - 每当我尝试在我的 Pycharm 上安装 conda 时都会出现错误,那么我将如何在我的 pycharm 上安装 conda?
- c# - unity GetKeyDown 好像注册了两次
- create-react-app - gh-pages 从主分支中删除我的源文件