reactjs - 为什么这不在 React 表单 onSubmit 函数的范围内?

标签 reactjs

在我的 React 组件中,我有一个带有 onSubmit 函数的表单

<form className="form-horizontal" name="taskForm" onSubmit={this.submitTask}>

submitTask(e) {

  e.preventDefault();
  console.log(this.props);  // undefined
  console.log(this) // window object
}

出于某种原因this.props当我使用表单 onSubmit 时,不在范围内。当我 console.log(this.props)在构造函数中,props 正常注销。

当我 console.log(this)它是窗口对象。如何获取 React 组件的作用域?

最佳答案

这是一个更广泛的问题,因为当您使用其他组件事件(例如 onClick、onChange、onSubmit)时,您会注意到与此类似的行为

在文档中有关于它的注释:

https://facebook.github.io/react/docs/reusable-components.html#no-autobinding

Methods follow the same semantics as regular ES6 classes, meaning that they don't automatically bind this to the instance. You'll have to explicitly use .bind(this) or arrow functions =>.

正如所描述的,您必须绑定(bind)这些方法或使用箭头函数。 如果您选择绑定(bind),那么您可以在构造函数中绑定(bind)或严格在渲染组件中绑定(bind)。

在构造函数中:

constructor(props) {
  super(props);
  this.submitTask = this.submitTask.bind(this);
}

在渲染组件中:

<form className="form-horizontal" name="taskForm" onSubmit={this.submitTask.bind(this)}>

使用箭头函数,您可以将submitTask内容传递给箭头函数:

<form className="form-horizontal" name="taskForm" onSubmit={e => {
  e.preventDefault();
  console.log(this.props);  // undefined
  console.log(this) // window object
}}>

关于reactjs - 为什么这不在 React 表单 onSubmit 函数的范围内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35881959/

相关文章:

javascript - 无法在子组件中访问 c​​lass.contextType

node.js - 如何使用 React 入门套件让调试器识别 webstorm 10 中的源映射

javascript - 无法在 chrome-extension 中从 executeScript 发送数据

javascript - 我如何对对象进行冒泡排序?

css - react 中的内联CSS无法动态工作

reactjs - 显示通过API返回的错误-React Final Form

javascript - ReactJS:访问子方法

javascript - 将 React 组件渲染到 Fancybox

javascript - 浏览器中未定义的 React 组件 - ES6 导入/导出

javascript - ReactJS 生命周期(v. 16.4)中传递数据的正确模式是什么