-2

I can not image the use case of a function was not bond by this object. I think all of the functions need to be bond by this. So why Reactjs doesn't set bind(this) by default? For example the following code, if I didn't set bind(this) the functions would be useless, right?

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = { username: '' }
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(ex) {
    this.setState({ username: event.target.value })
  }

  handleSubmit(event) {
    event.preventDefault()
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type="text"
          value={this.state.username}
          onChange={this.handleChange}
        />
        <input type="submit" value="Submit" />
      </form>
    )
  }
}
Javier Silva Ortíz
  • 2,426
  • 1
  • 8
  • 19
Jack
  • 4,626
  • 8
  • 46
  • 98
  • 4
    Because there are cases where you want that to not happen. – Kevin B Oct 17 '19 at 18:19
  • 1
    There are ways to minimize the boilerplate, like using arrow functions in class properties, which once transpiled are automatically bound to the class instance. – Emile Bergeron Oct 17 '19 at 18:21
  • Actually handlers you can make just anonymous in a component which will not be populated much in application... Then their this will always be equal to class this – Dmitry Reutov Oct 17 '19 at 18:23
  • 1
    You dont need to bind functions if you use them only inside component, and react can not be sure if function is handler or not – Dmitry Reutov Oct 17 '19 at 18:25
  • 1
    Is not really react whose isn't binding the function, the problem is that the function is used as an event handler, and by default when the event is triggered, the browser calls the handler by assigning the `this` value to the element that triggered the event. – Christian C. Salvadó Oct 17 '19 at 18:25

1 Answers1

2

if you dont want to bind this in the constructor try using function as arrow function it will automatically bind this object.You need not to explicitly do that.Something like this

 handleChange =(ex)=> {
    this.setState({ username: event.target.value })
  }
Ayushi Keshri
  • 719
  • 5
  • 17