[英]React onChange set but input still read-only
I am working on form in ReactJs and I am populating the input field with value from state. But my input field is being created as readonly.我正在处理 ReactJs 中的表单,并使用 state 中的值填充输入字段。但是我的输入字段被创建为只读。 Even though I set the onChange function.
即使我设置了 onChange function。
handleNameChange(event) {
myEvent.name = event.target.value;
}
render(){
return(
<input type="text" id="eventName" className="form-control" onChange={this.handleNameChange.bind(this)} value={this.state.name}/>
);
}
I do not understand this behavior.我不明白这种行为。 Can someone please explain?
有人可以解释一下吗? Thank you
谢谢
Reason is you are using a state variable to store the text field value, but you are not updating the value on onChange event, because of that your text field is read only, Try this: 原因是您使用状态变量来存储文本字段值,但是您没有更新onChange事件的值,因为您的文本字段是只读的,请尝试以下操作:
handleNameChange(event) {
this.setState({name: event.target.value});
}
render(){
return(
<input type="text" id="eventName" className="form-control" onChange={this.handleNameChange.bind(this)} value={this.state.name}/>
);
}
To change the state of a component in React, you will need to use this.setState
. 要在React中更改组件的状态,您需要使用
this.setState
。 After you call that method, the component will be re-rendered with the new data you've set. 调用该方法后,将使用您设置的新数据重新呈现该组件。 Here's your example using
setState
: 这是使用
setState
的示例:
class Example extends React.Component { constructor() { super(); this.state = { name: 'Harambe' }; this.handleNameChange = this.handleNameChange.bind(this); } handleNameChange(event) { this.setState({ name: event.target.value }); } render() { console.log(this.state); return( <input type="text" id="eventName" className="form-control" onChange={this.handleNameChange} value={this.state.name}/> ); } } ReactDOM.render(<Example/>, document.getElementById('View'));
<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="View"></div>
incase if you are using functional based components, then you can solve this problem by using useState
hook this way如果你使用的是基于功能的组件,那么你可以通过使用
useState
hook 这种方式来解决这个问题
import {useState} from "react";
export default Example = (props) =>{
let [text, setText] = useState(props.value)
function update(e){
setText(e.current.value);
// here you can add whatever additional functionality that you want to add.
props.value = e.current.value;
}
return (
<><input type="text" value={text} onChange={update} /></>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.