![](/img/trans.png)
[英]Onblur event with setState doesn't allow onClick of child in React
[英]react onBlur setState doesn't work (jsbin)
我一直在努力調試反應。 在 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> : ''}
);
}
}
有什么更好的方法來調試反應嗎? 如果當用戶離開基於狀態的輸入時,我只想顯示錯誤消息。
每當在構造函數中綁定方法時,盡量使用相同的名稱來避免此類錯誤,如果username
不為空,我認為您需要將狀態值重置為false
,請嘗試以下代碼:
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
首先,您必須僅從組件(或數組,但不太常見)中返回一個頂級元素。 將渲染輸出包裝在單個元素中:
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 Bin 不會很好地將 Babel 錯誤傳播給用戶。 我建議不要使用它,而是使用 Babel 和 Webpack 設置本地開發環境。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.