javascript - 请求解释 React 中“将事件处理程序绑定到类实例”的概念
问题描述
嗨,我是全栈 Web 开发的新手,我正在尝试理解React 中的“将事件处理程序绑定到类实例”的概念
class Foo extends React.Component{
constructor( props ){
super( props );
this.handleClick = this.handleClick.bind(this); // <- why?
}
handleClick(event){
// your event handling logic
}
render(){
return (
<button type="button"
onClick={this.handleClick}>
Click Me
</button>
);
}
}
ReactDOM.render(
<Foo />,
document.getElementById("app")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>
解决方案
反应文档https://reactjs.org/docs/handling-events.html
您必须小心 JSX 回调中 this 的含义。在 JavaScript 中,默认情况下不绑定类方法。如果您忘记绑定 this.handleClick 并将其传递给 onClick,则在实际调用该函数时 this 将是未定义的。
这不是 React 特有的行为;它是 JavaScript 中函数工作方式的一部分。一般情况下,如果引用的方法后面不带 (),比如
onClick={this.handleClick}
,则应该绑定该方法。
class Foo extends React.Component{
constructor( props ){
super( props );
}
handleClick(event){
console.log(this); // 'this' is undefined
}
render(){
return (
<button type="button" onClick={this.handleClick}>
Click Me
</button>
);
}
}
ReactDOM.render(
<Foo />,
document.getElementById("app")
);
要解决,您可以绑定this
到类构造函数上的函数
constructor( props ){
super( props );
this.handleClick = this.handleClick.bind(this);
}
或公共类字段语法(箭头函数)
class Foo extends React.Component{
handleClick = () => {
console.log(this);
}
render(){
return (
<button type="button" onClick={this.handleClick}>
Click Me
</button>
);
}
}
推荐阅读
- c# - 从文本中获取字符串加上一定数量的字符
- typescript - 使用纱线工作区导出枚举时出现意外的令牌错误
- android - Android Room with Hilt - 如何在创建数据库后填充表?
- javascript - 如何停止调用我设置为每 x 秒调用一次的函数?
- java - IOUtils.ToByteArray(InputStream) 是线程安全的吗?
- android - 如何让 Android 布局文件知道选择了不同的语言
- cookies - 使用 axios 时,cookie 不会保存在浏览器中,但会保存在 Insomnia 中
- c++ - 有什么方法可以直接将整数的按位表示形式转换为 C++ 中的向量?
- javascript - 将引号添加到值数组
- math - 前缀和后缀 GCD 如何解决所选的一个问题