2017-06-15 151 views
1

我一直試圖改變輸入字段的值後,我從從SelectUI庫選擇項目,但我還沒有成功,但就我搜索就可以了,我寫的一切好像它應該是。更改輸入字段的值 - 反應

這是我用來改變價值;

var element = ReactDOM.findDOMNode(this.refs._deviceId); 
    element.setAttribute('value', 'deneme'); 
    console.log(element); 

這是輸入字段;

   <div className="form-group row"> 
       <label className="col-md-2 control-label">Device ID</label> 
       <div className="col-md-10"> 
        <input type="text" className="form-control" id="deviceId" placeholder="Device ID" ref="_deviceId" /> 
       </div> 
       </div> 

我安慰了元素變量後,我選擇該項目,以檢查一切正常,似乎是沒有問題的。

這裏是控制檯日誌;

正如你看到的,值放置成功,但在屏幕上,什麼也沒有發生輸入字段。

+0

因爲組件不被重新渲染>使用狀態成員並將它傳遞給輸入。你還需要監聽輸入的變化相應地更新您的狀態 –

回答

2

設置了value屬性後,需要重新渲染組件。才反應過來重新呈現的組件當它檢測到的狀態的變化。因此,與其使用狀態可變

//Declare the state variable 

this.state = { 
    inputValue: '' 
}; 

//Use a lifecycle event or your own method to change the value of that state by using the setState method as- 

someMethod() { 
    this.setState({ 
     inputValue: 'deneme' 
    }); 
} 

//In HTML use the above state as- 
<input type="text" className="form-control" id="deviceId" placeholder="Device ID" ref="_deviceId" value={this.state.inputValue} /> 

記住使用的setState方法來改變狀態,以便重新組成渲染才能進行。

OR

您可以撥打this.forceUpdate()強行重新呈現組件。