JavaScript this

问题描述 投票:0回答:3

在Web浏览器中,该地址为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'));

为什么两个结果不同?请参考两个代码示例的注释。登录到控制台的第一个代码是按钮的this值,登录到控制台的第二个代码未定义为this的值。他们不应该一样吗?它们为什么不同?

javascript reactjs this
3个回答
0
投票
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类中,您应该自己绑定此:

<button onClick={this.tap.bind(this)}>

强调我的。

由于您正在使用ES6类,因此上述适用:您需要自己绑定它。


0
投票
看起来您与javascript OOP概念有点不一样。这是因为可以将全局-功能-块划分为范围。如果要使用javascript查看此对象,它将为您提供功能范围内的功能。如果要在全局范围内查看此对象,它将为您提供窗口对象。如果您在React js中使用基于类的组件,这将为您提供类本身。之所以在react js的render方法期间未定义此对象的原因是,因为它是react js附带的一种方法。

[在您专注于react js之前,建议您研究一下javascript中的含义,以便更好地理解。

这样,他就知道所有细节,您也没有任何问题。您要做的基本事情是找出JavaScript的类概念实际上是基于什么的。因此,更好地研究基于原型的继承以及es6附带的类概念。

首先,学习这些概念很重要。祝你好运!


-1
投票
为您的React类编写一个构造函数:

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

[您需要在课堂上致电super,然后再尝试使用this。签出this post来说明在React类中使用super

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

© www.soinside.com 2019 - 2024. All rights reserved.