简体   繁体   中英

Attach an onchange event listener to a textarea

I am trying to attach an onchange event listener to a textarea that updates it's state with the new value.

Here's the code using inline functions:

class Textarea extends React.Component {
  constructor(props){
    super(props);
    this.handleScroll = this.handleScroll.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.state = {value: ''};
  }


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

  render(){
    //alert("textarea rendered");
    return (
      <textarea value={this.state.value} onChange={()=>{this.handleChange}}></textarea>
    );
  }
}

The textarea value doesn't update with the above code but it does if I replace the onChange in the below manner:

<textarea value={this.state.value} onChange={this.handleChange}></textarea>

Instead of updating state, if I change the handleChange function to throwing an alert each time the value changes inside the textbox, it works if I remove the value attribute from the textbox.

React.Component doesn't bind every function to this . It only binds this with the life cycle methods of the react.

Arrow functions: When you use arrow functions the function will automatically get bound to this . It's arrow functions feature.

But in your first attempt, you tried the arrow function () => { this.handleChange } which is similar to

function () {
   this.handleChange; // this is not being called at all.
}

The above syntax literally does nothing. try this instead (evt) => { this.handleChange(evt); } (evt) => { this.handleChange(evt); } which is similar to

function (evt) {
   this.handleChange(evt); // The event will get passed to the function here.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM