当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - 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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: