javascript 更改输入元素的只读属性:ReactJS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46093596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change readonly attribute of input element: ReactJS
提问by
I want to add or remove an attribute from an html input element.
我想从 html 输入元素中添加或删除属性。
What i'm done is this:
我所做的是这样的:
constructor(props) {
super(props);
this.state = {inputState: 'readOnly'};
}
And the render function:
和渲染功能:
<input className="form-control" type="text" value={floor} {...this.state.inputState} />
As you can see i want set the "readOnly" attribute on the input element. But now i get an error which says:
如您所见,我想在输入元素上设置“只读”属性。但现在我收到一个错误消息:
Unknown props
0,1,2,3,4,5,6,7on tag. Remove these props from the element
未知道具
0, ,1,2,3,4,5,6,7在标签上。从元素中删除这些道具
When an user is clicking on the input element it should become editable, so i want to dynamicly change this attribute.
当用户单击 input 元素时,它应该变得可编辑,因此我想动态更改此属性。
But how can i do that?
但是我该怎么做呢?
采纳答案by Mayank Shukla
To control the mode of inputelement define readOnlyattribute with it and control it's value by state variable, Whenever you update the state value react will re-render the component and it will change the mode on the basis of state value.
为了控制input元素定义readOnly属性的模式,并通过状态变量控制它的值,每当您更新状态值时,react 将重新渲染组件,并根据状态值更改模式。
Check this example:
检查这个例子:
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'/>
回答by An Nguyen
Try this instead:
试试这个:
this.state = { inputState: { readOnly: true }};
this.state = { inputState: { readOnly: true }};
回答by bennygenel
You can try this.
你可以试试这个。
constructor(props) {
super(props);
this.state = {readOnly: true};
}
render() {
return (<input className="form-control" type="text" value={floor} readOnly={this.state.readOnly} />)
}

