我是 React 的新手,我正在通过构建一个简单的测试应用程序来学习,我在其中遇到了“this”绑定(bind)问题。我昨天使用“create-react-app”创建了这个应用程序包,所以 babel 和所有其他插件应该是最新的。
现在谈谈我的问题: 如果我使用箭头函数在类中声明一个方法来绑定(bind)“this”,那么一切正常
class abc extends Component {
constructor (props) {
super(props);
this.state = {};
}
someMethod = () => {
console.log(this); //"this" works fine
}
}
但是当我尝试在构造函数中使用显式“this”绑定(bind)来执行相同操作时,绑定(bind)不起作用并且“this”未定义:
class abc extends Component {
constructor (props) {
super(props);
this.state = {};
this.someMethod.bind(this)
}
someMethod () {
console.log(this); //"this" is undefined
}
}
你能帮我理解为什么它不起作用吗?我阅读了一些关于 JS 和 React 中“this”绑定(bind)的文章和书籍章节,我认为上面的两个代码示例应该完全相同。
最佳答案
class abc extends Component {
constructor (props) {
super(props);
this.state = {};
this.someMethod= this.someMethod.bind(this) //modified this line
}
someMethod () {
console.log(this);
}
}
这会起作用,我已经做了更改
关于javascript - React - 在构造函数中绑定(bind) this 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55429989/