在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的值。他们不应该一样吗?它们为什么不同?
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类,因此上述适用:您需要自己绑定它。
[在您专注于react js之前,建议您研究一下javascript中的含义,以便更好地理解。
这样,他就知道所有细节,您也没有任何问题。您要做的基本事情是找出JavaScript的类概念实际上是基于什么的。因此,更好地研究基于原型的继承以及es6附带的类概念。
首先,学习这些概念很重要。祝你好运!
constructor(props) {
super(props);
// Bind the function here
this.handleClick = this.handleClick.bind(this);
}
[您需要在课堂上致电super
,然后再尝试使用this
。签出this post来说明在React类中使用super
。您还需要像上面显示的那样绑定您的函数,或者在调用该函数时使用箭头函数。