2017-05-12 35 views
-4

我的代碼是在這裏:https://jsfiddle.net/woyuditan26/bgwrfLxh/React的狀態如何工作?

 this.setState((prevState) => ({ 
     tasks: prevState.tasks.concat(newTask), 
     text: '' //// why the input text is not cleared when I clicked the button ? 
     })); 

爲什麼當我點擊按鈕輸入文本時,不能解除?

+0

你在哪裏使用'text'? –

+0

我們是否有「debug-my-code」標籤或類似的標籤? – mvw

+1

我建議你閱讀[react/docs/forms](https://facebook.github.io/react/docs/forms.html)。 – koox00

回答

2

原因是,您正在使用uncontrolled element(因爲您沒有使用輸入元素定義value屬性),因此要將其設置爲controlled element,您需要使用input元素指定值prop。

像這樣:

<input type="text" value={this.props.text} onChange={this.handleTextChange}/> 

檢查工作fiddle