我有一个问题..请告诉我..
import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
}
handleClick = () => {
console.log("clicking")
};
render() {
return (
<div>
<ul>
{this.state.letters.map((letter) => (
<li onClick={() => this.handleClick()}> // when clicking li, it works.
<li onClick={() => handleClick()}> // when clicking li, it does not works why????
hello
</li>
))}
</ul>
</div>
);
}
}
export default App;
这是非常简单的代码。
我的问题是为什么我们要这样写。handleClick ??
在我看来,
- 点击 li 标签时。
- this.handleClick 函数在箭头函数中!!
- 所以,箭头函数会自动绑定(bind) this
- (在本例中,这绑定(bind)到应用程序组件)
- 因此,在箭头函数中,只需找到handleClick即可,(//在我看来)
- 因为可以找到this.handleClick!
- 但是,仅仅编写handleClick是行不通的..?为什么 ?? //handleClick 未发现错误...
你能解释一下为什么会发生这种情况吗?
另外..
如果我更改了代码,例如
我们可以看到这是App组件。 同样在App组件中,我们可以看到handleClick函数...
所以,这与应用程序组件绑定(bind), 然后我认为在箭头函数中,可以找到handleClick()函数。但没有找到...为什么??
最佳答案
您似乎对箭头函数的含义感到困惑,用您的话说“自动绑定(bind)它”。从技术上讲,事实并非如此。请参阅 MDN 文章: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
它们不会自动绑定(bind) this
,它们只是不创建新的 this
绑定(bind)(与函数相反,函数本身会创建一个新的 this
绑定(bind))。虽然您可能认为它是“自动”绑定(bind) this
,但事实并非如此。但关键的一点是,它只影响箭头函数范围内 this
的含义。它与函数外部的 this
无关。因此,您将 handledClick
定义为箭头函数这一事实与您是否可以使用 this
访问它无关。它只影响 this
在函数本身中引用的内容。
所有这些都解释了为什么调用 this.handleClick
会在您的 render
中起作用,但尝试调用 handleClick
却不起作用。 render
范围内没有函数 handleClick
。有一个 this
(组件的实例),它恰好有一个 handleClick
方法。
在此上下文中使用箭头函数非常有用,因为您不必重新绑定(bind)它。如果您的 handleClick
函数需要访问 this.state
或 this.props
,它就能够做到。如果您将其定义为标准函数
,则需要重新绑定(bind)它,以便在调用时可以使用正确的this
。
正如其他人指出的那样,您的代码可能无论如何都无法工作。您应该删除包裹它们的箭头函数。事实上,您只是调用一个返回 handleClick
函数的函数,而不是调用它。
关于javascript - 在React中,为什么我们在箭头函数中调用this?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64254472/