Skip to content Skip to sidebar Skip to footer

How Do I Access Both The Class And The Calling Object In An Es2015 Class Method?

This is a beginner React.js / ES2015 question. I have some HTML that displays a list of book names: class BookList extends React.Component { render() { return (

Solution 1:

Bind it to your instance, and use event.target or event.currentTarget to access the TextField; this is shown in the docs here.

Actually, I think there's a standard React way to hook it up so you don't have to do the bind explicitly (which would be better; binding is cumbersome): When rendering, use onChange={this.onBookNameChange}.

Here's the example from the docs:

getInitialState: function() {
  return {value: 'Hello!'};
},
handleChange: function(event) {
  this.setState({value: event.target.value});
},
render: function() {
  var value = this.state.value;
  return<inputtype="text"value={value}onChange={this.handleChange} />;
}

Note handleChange's use of this and event.target.

target and currentTarget doesn't matter if the handler is bound to an element (like input type="text") that can't contain other elements, but can matter for ones that can: currentTarget is the element that you bound the handler to (what you'd see as this if you were using this for something else). target is the element where the event occurred, which can be a descendant element. Think a div with a span in it: if you've hooked click on the div, and someone clicks the span, target will be the span and currentTarget will be the div.

So when replacing this with something from event, currentTarget would be the default thing to reach for to get an equivalent to this. target is really useful for delegation.

Solution 2:

You can bind multiple values to the

onEnterKeyDown={this.onBookNameChange}

It could look like this

onEnterKeyDown={this.onBookNameChange.bind(this, book.name}

In your function it would look like this:

onBookNameChange(name, ev) {
  console.log(this);
  console.log(ev);
  console.log("name: " + name);
}

Post a Comment for "How Do I Access Both The Class And The Calling Object In An Es2015 Class Method?"