我想在 html 输入元素中添加或删除属性。
我所做的是这样的:
constructor(props) {
super(props);
this.state = {inputState: 'readOnly'};
}
以及渲染函数:
<input className="form-control" type="text" value={floor} {...this.state.inputState} />
如您所见,我想在输入元素上设置“readOnly”属性。 但现在我收到一条错误消息:
Unknown props
0
,1
,2
,3
,4
,5
,6
,7
on tag. Remove these props from the element
当用户单击输入元素时,它应该变得可编辑,因此我想动态更改此属性。
但是我该怎么做呢?
最佳答案
为了控制input
元素的模式,定义readOnly
属性并通过状态变量控制它的值,每当你更新状态值时,react都会重新渲染组件它会根据状态值改变模式。
检查这个例子:
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'/>
关于javascript - 更改输入元素的只读属性: ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46093596/