我一直在挣扎于调试反应。在jsbin中,我不可能知道是什么错误,当我打开我的浏览器的控制台或控制台时,没有明确的指示我的错误是关于什么的。
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> : ''}
);
}
}是否有更好的调试方式来响应?我只想显示错误消息,如果当用户离开输入基础的状态。
发布于 2017-01-20 06:11:08
每当绑定构造函数中的方法时,尝试使用相同的名称来避免此类错误,如果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
发布于 2017-01-20 06:02:21
首先,必须只从组件(或数组)返回一个顶层元素,但这并不常见)。将呈现的输出封装在一个元素中:
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和createClass()
阻止代码加载的错误来自包装元素。JS没有很好地向用户传播Babel错误。我建议不要使用它,而是与巴贝尔和Webpack一起建立一个当地的发展环境。
https://stackoverflow.com/questions/41756997
复制相似问题