score:3

Accepted answer

you can't bind this in arrow functions. this falls through to the parent scope.

you could make it a non-arrow function:

function handleinputchange(key, value) { this.setstate(key: value) }

but i'd suggest making it a method on the class. defining a function that references this is tricky to read, because you never know what this will be when it executes, making it hard to read the function at a glance.

score:0

since you are calling this function inside the class, it's better to define it as a method within the class instead of defining it outside, so that the this issue is less of a, well, issue.

inside the class makes it fairly straightforward:

constructor(props) {
this.handleinputchange = this.handleinputchange.bind(this)
}

handleinputchange() {
   //code
}

or if you want to avoid having to do the messy bind method, you can use an arrow function for the method:

handleinputchange = () => {
  console.log('this is: ', this);
}
...

render() {
  return(
    <button onclick={this.handleinputchange}>click</button>
   );
}

reference react handling events

score:1

arrow functions do not have their own this, if you use call([this obj], args), apply([this obj], args), any "this" argument is ignored. i guess the same applies to bind(obj), it doesn't bind this to the object you provided because it doesn't have its own this.

this inside arrow functions is decided by this in the lexical scope where the arrow function is defined. if you define your handleinputchange in global scope, this inside is the global object(in browser it's window), that's the reason you get the error.

if you want to use bind, you can define the function like this

function handleinputchange(key, value) { this.setstate(key: value) }

when you call bind, this will be set to the object you provided in bind.


Related Query

More Query from same tag