gpt4 book ai didi

javascript - React - 在构造函数中绑定(bind) this 不起作用

转载 作者:行者123 更新时间:2023-11-30 19:40:44 29 4
gpt4 key购买 nike

我是 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com