2016-08-02 126 views
12

我在下面使用了一個變量。使用Reactjs清除輸入字段?

var newInput = { 
    title: this.inputTitle.value, 
    entry: this.inputEntry.value  
}; 

這是我的輸入字段使用。

<input type="text" id="inputname" className="form-control" ref={el => this.inputTitle = el} /> 
    <textarea id="inputage" ref={el => this.inputEntry = el} className="form-control"></textarea> 
     <button className="btn btn-info" onClick={this.sendthru}>Add</button> 

一旦我激活{this.sendthru}我想清除我的輸入字段。但是,我不確定如何去做。

此外,正如本例中所示,有人指出我應該使用ref屬性作爲輸入值。我不清楚是什麼意思。 el在這種情況下有什麼意義?

回答

14

讓我假設你已經完成了'sendThru'函數的'this'綁定。

下面的函數在方法被觸發時清除輸入字段。

sendThru() { 
    this.inputTitle.value = ""; 
    this.inputEntry.value = ""; 
} 

參考文獻可以寫爲內聯函數表達式:

ref={el => this.inputTitle = el} 

el地方指的是組件。

當refs如上所述寫入時,React每次在每次更新時都會看到一個不同的函數對象,ref將在用組件實例調用之前立即用null調用。

瞭解更多關於here

+0

你能擴大一點關於sendthru函數的'this'綁定是什麼意思?因爲,當我點擊時,我得到一個錯誤'不能讀取屬性值undefined' –

+0

明白了。而不是使用'this.refs.inputTitle.value ='「'我使用了'this.inputTitle =」「',這有訣竅。 –

+1

'sendThru'是onClick函數的事件處理程序,React建議在您的構造函數方法中綁定'this'引用。例如'構造函數(){this.sendThru = this.sendThru。bind(this)}',或者如果你沒有使用ES6類作爲反應組件,你可以在你的渲染方法中將這個關鍵字綁定爲'onClick = {this.sendThru.bind(this)}' –

5

我不太確定語法{el => this.inputEntry = el},但是在清除輸入字段時,您需要像上面提到的那樣指定ref。

<input type="text" ref="someName" /> 

然後在onclick功能你使用的輸入值完成之後,只要用...

this.refs.someName.value = ''; 

編輯

其實{EL => this.inputEntry = el}與我相信的相同。也許有人可以糾正我。 el的值必須從某處傳入,以作爲參考。

function (el) { 
    this.inputEntry = el; 
} 
6

輸入標籤申報值屬性(即value= {this.state.name}),如果你想清楚這個輸入淡水河谷,你必須使用this.setState({name : ''})

PFB工作代碼,供大家參考:

<script type="text/babel"> 
    var StateComponent = React.createClass({ 
     resetName : function(event){ 
      this.setState({ 
       name : '' 
      }); 
     }, 
     render : function(){ 
      return (
       <div> 
        <input type="text" value= {this.state.name}/> 
        <button onClick={this.resetName}>Reset</button> 
       </div> 
      ) 
     } 
    }); 
    ReactDOM.render(<StateComponent/>, document.getElementById('app')); 
</script>