简体   繁体   中英

react onBlur setState doesn't work (jsbin)

I've been struggling with debugging react. In jsbin, there's no way I can know what error it is, when I open the console or console of my broswer there's no clear indication of what my error is about.

http://jsbin.com/doletanole/1/edit?html,js,console,output

class HelloWorldComponent extends React.Component {
  constructor() {
    super()
    this.getInput = this.focusHandler.bind(this)
    this.state = {hasError:false}
  }
  focusHandler(e) {
    if(e.target.value === ''){
      this.setState({hasError:true})
    }
  }
  render() {
    return (      
      <input placeholder="username" type="text" onBlur={this.focusHandler}/>
{this.state.hasError ? <span>Username is required</span> :  ''}  
    );
  }
}

Any better way to debug react ? I just want to show the error msg if when the user go away of the input base on the state.

Whenever binding the methods in the constructor, try to use the same name to avoid these kind of mistakes, i think you need to reset the state value to false if the username is not blank, Try this Code:

class HelloWorldComponent extends React.Component {
  constructor() {
    super()
    this.focusHandler = this.focusHandler.bind(this)
    this.state = {hasError:false}
  }
  focusHandler(e) {
    this.setState({hasError: e.target.value != '' ? false : true});
  }
  render() {
    return (    
      <div>  
         <input placeholder="username" type="text" onBlur={this.focusHandler}/>
         {this.state.hasError ? <span>Username is required</span> :  ''}  
      </div>
     );
  }
}

Check working example: http://jsbin.com/cozenariqo/1/edit?html,js,console,output

First of all, you must return only one top level element from a component (or an array, but that's less common). Wrap your rendered output in a single element:

render() {
    return (
        <div>
            <input placeholder="username" type="text" onBlur={this.focusHandler}/>
            {this.state.hasError ? <span>Username is required</span> :  ''}  
        </div>
    );
}

Secondly, you're not correctly binding the focusHandler event. Change it to onBlur={this.focusHandler.bind(this)} . Suggested reading:React, ES6, Autobinding, and createClass()

The error blocking your code from loading was from the wrapping element. JS Bin does not propagate Babel errors to the user well. I would suggest not using it and set up a local development environment with Babel and Webpack instead.

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