为什么这不在 React 形式的 onSubmit 函数范围内? [英] Why is this not scoped in React form onSubmit function?

查看:41
本文介绍了为什么这不在 React 形式的 onSubmit 函数范围内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my React component I have a form with onSubmit function

submitTask(e) {

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

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

For some reason this.props is not in scope when I use form onSubmit. When I console.log(this.props) in the constructor, props logs out normally.

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

When I console.log(this) it is the window object. How do I get the scope of the react component?

推荐答案

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

This is more broad problem, because similar behavior with this you will notice when you use other component events for example (onClick, onChange, onSubmit)

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

In documentation there is note about it:

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

方法遵循与常规 ES6 类相同的语义,这意味着它们不会自动将 this 绑定到实例.您必须明确使用 .bind(this) 或箭头函数 =>.

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 =>.

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

As it is described you have to bind those methods or use arrow functions. If you choose binding, then you can bind in constructor or strictly in rendered component.

在构造函数中:

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

在渲染组件中:

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

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

With arrow function you can pass submitTask content to arrow function:

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

这篇关于为什么这不在 React 形式的 onSubmit 函数范围内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆