Why is this not included in the React onSubmit form?

In my React component, I have a form with onSubmit function

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

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

For some reason this.props doesn't matter when I use the onSubmit form. When I console.log(this.props) in the constructor, the props exit the system as usual.

When I console.log(this) , this is a window object. How to get the scope of a reacting component?

+5
source share
1 answer

This is a wider problem, since you will notice a similar behavior with this, for example, when using other component events (onClick, onChange, onSubmit)

The documentation has a note about this:

https://facebook.imtqy.com/react/docs/reusable-components.html#no-autobinding

Methods follow the same semantics as regular ES6 classes, which means that they do not automatically associate this with an instance. You will need to explicitly use .bind (this) or arrow functions =>.

As described, you need to link these methods or use the arrow functions. If you select a snap, you can snap it in the constructor or strictly in the rendered component.

In the constructor:

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

In the rendered component:

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

Using the arrow function, you can pass the contents of submitTask to the arrow function:

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

Source: https://habr.com/ru/post/1244703/


All Articles