为什么提取图像按钮onClick
函数可以在函数表达式中使用,而不能在同一调用方法中使用函数声明。
class FetchButtom extends Component {
async fectchImage() {
const IMAGE_API = 'Some Image API';
try {
const images = await fetch(IMAGE_API);
const json = await images.json();
console.log(this);
this.props.addImage(json.items);
} catch (error) { }
}
fectchImageExpression = async () => {
const IMAGE_API = 'Some Image API';
try {
const images = await fetch(IMAGE_API);
const json = await images.json();
console.log(this);
this.props.addImage(json.items);
} catch (error) { }
}
render() {
return (
<div>
<button
// console.log(this); -> this point to FetchButtom
onClick={() => this.fectchImage()}
// This will no trigger fectchImage runs
onClick={() => this.fectchImage}
// TypeError: Cannot read property 'props' of undefined
onClick={this.fectchImage}
// Working perfectly, same as onClick={() => this.fectchImage()}
onClick={() => this.fectchImageExpression()}
// This will no trigger fectchImageExpression runs
onClick={() => this.fectchImageExpression}
// Working perfectly, same as onClick={() => this.fectchImage()}
onClick={this.fectchImageExpression}
>
Fetch image
</button>
</div>
);
}
}
所以,我的问题是为什么函数表达式使这2种情况在{() => this.fectchImageExpression()}
和{this.fectchImageExpression}
,函数声明中仅在{{1 }}
答案 0 :(得分:1)
为什么起作用:
使用箭头功能,对于属性表达式也是如此,
您正在用词法(从周围的声明上下文)严格绑定 this 。
为什么不起作用:
不同的是,您将从调用该函数的作用域中继承 this ,而您将丢失这些方法。
答案 1 :(得分:0)
onClick
收到一个函数声明-() => this.fectchImage()
是一个匿名函数,被调用时将运行this.fectchImage
。
将this.fectchImageExpression
分配给onClick
时,您将传递函数而不运行它,而单击该函数将运行传递的this.fectchImageExpression
。
当您将onClick
分配给() => this.fectchImageExpression
时,这是一个匿名函数,仅具有对this.fectchImageExpression
的引用,但没有调用它。因此,似乎它什么也没做。