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

标签 javascript reactjs

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

相关文章:

javascript - 为什么编译器找不到 'axios'

javascript - 页眉/页脚之间的内容

reactjs - 如何使用片段标识符(哈希链接)创建 react 选项卡导航栏链接?

javascript - React OIDC-Client IE Promise 未定义

c# - 循环变量上的闭包的正确语义是什么?

javascript - 这是检测 react 组件中第一次渲染的正确方法

javascript - 从数组中的 JSON 导出结果

javascript - 我得到体育冠军和第三名的空值

javascript - rails/JavaScript : How to inject rails variables into (very) simple javascript

javascript - 检查 div 值并更新 React 中的类