【发布时间】:2019-05-18 06:54:18
【问题描述】:
根据我的理解,箭头函数应该与创建它的上下文具有相同的范围。 就像下面一个返回:“这是绿色大号的框号”,我明白了。
let box6={
color:'green',
position:1,
font:'big',
clickMe:function(){
return ()=>{
let str='This is the box number '+this.color+' '+ this.font;
console.log(str)
} }
}
但是在 React 类中,handleClick 箭头函数是在类 LoggingButton 中定义的,它假设与它具有相同的作用域,但在控制台中,它返回:这是 LoggingButton,我认为它应该返回全局作用域或任何作用域级别高于 LoggingButton。 为什么会这样? 非常感谢!!!
class LoggingButton extends Component {
handleClick=()=>{
console.log('this is :', this)
}
render() {
return (
<div className="App">
<button onClick={this.handleClick}>Click Me</button>
</div>
);
}
}
【问题讨论】:
-
您可能对
handleClick = …语法感到困惑。这实际上发生在构造函数中。 -
如果
handleClick是常规函数,则this的范围将在handleClick内。 “上一级”是LoggingButton。
标签: javascript reactjs class scope this