2017-09-07 88 views
1

我想添加或從html輸入元素中刪除屬性。更改輸入元素的只讀屬性:ReactJS

什麼,我所做的就是這樣的:

constructor(props) { 
    super(props); 
    this.state = {inputState: 'readOnly'}; 
} 

而且渲染功能:

<input className="form-control" type="text" value={floor} {...this.state.inputState} /> 

正如你可以看到我想要設置的輸入元素上參考「readOnly」屬性。 但現在我得到它說的錯誤:

未知道具01234567的標籤。從元素中移除這些道具

當用戶點擊輸入元素時,它應該變成可編輯的,所以我想動態地改變這個屬性。

但我該怎麼做?

+0

如果你真的想傳播的狀態。簡單地做到:'' – mersocarlin

回答

1

爲了控制input元件的模式定義readOnly屬性與它和控制它的通過狀態變量值,每次更新狀態值反應將重新呈現組件和它會改變的基礎上,模式狀態值。

檢查這個例子:

class App extends React.Component{ 
 
    constructor(){ 
 
    super(); 
 
    this.state = {readOnly: true} 
 
    this._click = this._click.bind(this); 
 
    } 
 

 
    _click(){ 
 
    this.setState(prevState => ({readOnly: !prevState.readOnly})) 
 
    } 
 
    
 
    render(){ 
 
    return <div> 
 
     <input readOnly={this.state.readOnly}/> 
 
     <button onClick={this._click}>Toggle</button> 
 
    </div> 
 
    } 
 
} 
 

 
ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 

 
<div id='app'/>

0

試試這個:

this.state = { inputState: { readOnly: true }};

0

你可以試試這個。

constructor(props) { 
    super(props); 
    this.state = {readOnly: true}; 
} 

render() { 
    return (<input className="form-control" type="text" value={floor} readOnly={this.state.readOnly} />) 
}