javascript - 代码中一行的 React-JavaScript 用途
问题描述
这是一个非常简单的问题,但我正在学习过程中,在阅读之后我找不到一个很好的解释,在下面的代码中:What is the purpose of the line:
this.buttonClicked = this.buttonClicked.bind(this);
如果我评论它,该程序仍在运行。很可能有一些副作用,但我还不知道......
class test extends React.Component {
constructor(props){
super(props)
//this.buttonClicked = this.buttonClicked.bind(this);
}
buttonClicked() {
alert("thank you!")
}
render() {
return (
<div>
<h2>{this.props.text}</h2>
<button onClick={this.buttonClicked}>click me!</button>
</div>
)
}
}
解决方案
this.buttonClicked = this.buttonClicked.bind(this);
这条线基本上允许你this
在你的buttonClicked()
函数中使用。
您不会注意到差异,因为您实际上并未this
在该功能中使用。
this
在buttonClicked()
注释掉绑定行的情况下尝试使用inside,您应该会收到错误消息。
为避免需要手动绑定,您可以使用箭头函数,例如:
buttonClicked = () => {
// do something with `this`
}
推荐阅读
- javascript - React Native 结构导致 Axios 循环 HTTP 请求
- node.js - firestore 云功能未触发
- python - 不知道如何修复损坏的 Python 安装
- python - 为什么在画布很小的情况下,turtle 会打开一个更小的屏幕?
- twilio - “Twilio 找不到具有指定发件人地址的频道”
- c# - 未显示 Swagger 响应描述
- gpu - OpenCL中是否有一些方法可以像cuda的时间函数一样计算内核时间
- android-studio - AndroidStudio kotlin AlertDialogue,带有 setItems 的微调器
- javascript - 那么如何将来自 react redux 的数组中所有对象的所有值相加呢?
- php - 使用 curl 下载的 pdf 文件 - 问题