首页 > 解决方案 > 类和反应组件中的 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 中,我得到了按钮对象。

谢谢 !

标签: javascriptreactjsclassthisarrow-functions

解决方案


您不必处理this. 但不要忘记绑定回调事件(关于事件的 React Doc)以始终拥有良好的参考

只需将其添加到App Component

  constructor(props) {
    super(props);
    this.logThisArr = this.logThisArr.bind(this);
    this.logThisReg = this.logThisReg.bind(this);
  }

推荐阅读