【问题标题】:JavaScript thisJavaScript 这个
【发布时间】:2020-05-18 22:01:54
【问题描述】:

在这个地址的网络浏览器中:https://www.w3schools.com/js/tryit.asp?filename=tryjs_arrow_function6,我删除了原始代码,并粘贴了这段代码:

<!DOCTYPE html>
<html>
<body>



<button id="btn">Click Me!</button>

<p id="demo"></p>

<script>


document.getElementById("btn").addEventListener("click", function() {
console.log(this) // **THIS LINE GAVE THE VALUE OF AS BUTTON**

});
</script>

</body>
</html>

在 React Stackblitz 中尝试了以下代码:

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';

class Foo extends React.Component{

  render(){
      return (
      <button type="button" onClick={function handleClick(event){
    console.log(this); // **THIS LINE GAVE THE VALUE AS UNDEFINED**
  }}>
        Click Me
      </button>
    );
  }
} 

render(<Foo />, document.getElementById('root'));

为什么两个结果不同?请参考两个代码示例的 cmets。第一个代码将按钮作为 this 的值记录到控制台,第二个代码将 undefined 作为 this 的值记录到控制台。他们不应该是一样的吗?为什么它们不同?

【问题讨论】:

标签: javascript reactjs this


【解决方案1】:

Quoting facebook react issue #5040:

class MyButton extends Component { 
   state = { tapped: false }

   tap() {
         this.setState({ tapped: true });  // --> 'this' here is undefined 
   }

   render() {
       return (
            <button onClick={ this.tap }>TAP ME</button> 
       )
   }
}

正如上面的评论所指出的,当从按钮的 onclick 调用 tap() 方法时,我收到一个错误,基本上告诉我“this”是未定义的。

答案:

React.createClass 在幕后为你自动绑定这个。

在 ES6 类中,你应该自己绑定这个:

&lt;button onClick={this.tap.bind(this)}&gt;

强调我的。

由于您使用的是 ES6 类,因此上述内容适用:您需要自己绑定它。

【讨论】:

    【解决方案2】:

    为你的 React 类编写一个构造函数:

      constructor(props) {
      super(props);
    
      // Bind the function here
      this.handleClick = this.handleClick.bind(this);
    
    }
    

    在尝试使用this 之前,您需要在班级中致电super。查看 this post,它解释了在 React 类中使用 super

    您还需要像我上面显示的那样绑定您的函数,或者在调用函数时使用箭头函数。

    【讨论】:

    • 这是不正确的。构造函数是完全可选的。
    • 调用前需要绑定函数。在构造函数中绑定,或者调用的时候使用箭头函数,就不用绑定了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-04
    • 2015-08-17
    相关资源
    最近更新 更多