简体   繁体   中英

ReactJS onChange event handler

I've got some confusion with React's event handler

I have a component like this, with handleChange handling onChange event:

var SearchBar = React.createClass({
    getInitialState(){
        return {word:''};
    },
    handleChange: function(event){
        this.setState({word:event.target.value});
        alert(this.state.word);
    },
    render: function () {
        return (
            <div style={{width:'100%',position:'0',backgroundColor:'darkOrange'}}>
                <div className="header">
                    <h1>MOVIE</h1>
                </div>
                <div className="searchForm">
                    <input className="searchField" onChange={this.handleChange}
                        value={this.state.word} type="text" placeholder="Enter search term"/>
                </div>
            </div>
        );
    }
});

It does work, but not the way I expect. In textfield, when I type the first character, it alerts empty string, when the second character is typed, it alerts a string with only first character, and so on, with string length of n, it alerts the string with n-1 length

What did I do wrong here? How should I fix it?

Use like this,

Js:

   this.setState({word:event.target.value}, function() {
    alert(this.state.word)
   });

Working Jsbin

I think it has something to do with state handling inside React.

I can come with two options to handle it.

Either:

handleChange: function(event) {
  this.setState({word: event.target.value});
  window.setTimeout(function() {
    alert(this.state.word);
  }.bind(this));
}

Or:

alertCurrentValue() {
  alert(this.state.word);
},
render: function () {
  this.alertCurrentValue();
  return ( ... )
}

Praveen Raj's answer is definitely the right way to go. Here is the documentation I found from the official React website on why you should access this.state inside the callback rather than right after setState():

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

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