Why is this not scoped in React form onSubmit function?

前端 未结 1 1982
一生所求
一生所求 2020-12-19 05:10

In my React component I have a form with onSubmit function

相关标签:
1条回答
  • 2020-12-19 05:24

    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

    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.

    In constructor:

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

    In rendered component:

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

    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
    }}>
    
    0 讨论(0)
提交回复
热议问题