反应onBlur setState不起作用(jsbin)

时间:2017-01-20 05:55:20

标签: javascript reactjs

我一直在努力调试反应。在jsbin中,我无法知道它是什么错误,当我打开我的broswer的控制台或控制台时,没有明确指出我的错误是什么。

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> :  ''}  
    );
  }
}

任何更好的调试方法?我只想显示错误信息,如果用户离开状态的输入基础。

2 个答案:

答案 0 :(得分:1)

每当绑定构造函数中的方法时,尝试使用相同的名称来避免这些错误,我认为如果false不为空,我需要将状态值重置为username,试试这个代码:

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>
     );
  }
}

检查工作示例:http://jsbin.com/cozenariqo/1/edit?html,js,console,output

答案 1 :(得分:0)

首先,您必须从组件(或数组中)返回一个顶级元素,但这不常见。将渲染的输出包装在一个元素中:

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

其次,您没有正确绑定focusHandler事件。将其更改为onBlur={this.focusHandler.bind(this)}。建议阅读:React, ES6, Autobinding, and createClass()

阻止代码加载的错误来自包装元素。 JS Bin不会很好地将Babel错误传播给用户。我建议不要使用它,而是用Babel和Webpack建立一个本地开发环境。

相关问题