javascript - 关键字 this 的值
问题描述
看看下面的代码:
class App extends React.Component {
go(){
console.log("Hello",this);
}
render() {
console.log("Hey",this);
return (
<button onClick={this.go}>Add profile</button>
);
}
}
为什么this
inside的值go
是未定义的?this
insiderender
是一个App
实例,因为我们调用inside 方法this.go
的值应该等于同一个实例。this
go
App
解决方案
您需要绑定go
或使用箭头功能:
export default class App extends React.Component {
go = () => {
console.log('Hello', this);
};
render() {
console.log('Hey', this);
return <button onClick={this.go}>Add profile</button>;
}
}
推荐阅读
- jpa - 使用 JPA 的 microprofile-config 自定义 ConfigSource
- awk - 如何在 AWK 中替换正则表达式?
- python - 谷歌搜索“龙珠壁纸”上的python网页抓取
- mysql - 没有互联网时无法通过 LAN 访问 mysql
- html - 为什么列数会在 4K 屏幕上的 Chrome 中呈现细线?
- jestjs - 将 Jest 步骤定义提取到单独的文件中
- python-3.x - 如何将 SalesForce 数据获取到 Python Panda 数据帧
- xamarin - xamarin - Android 以编程方式更改主题
- python - Keras 模型 LSTM 预测 2 个特征
- java - JavaFX SceneBuilder:加载自定义控件时出现 ClassNotFoundException