[英]What is the proper way to clear a React Form?
I have a form that has a few different type of elements (textbox, checkbox, etc.) that was created using Reactjs. I have been having a hard time trying to figure out how to clear a form.我有一个表单,其中包含一些使用 Reactjs 创建的不同类型的元素(文本框、复选框等)。我一直很难弄清楚如何清除表单。 I've googled and not really sure of those solutions.
我在谷歌上搜索过,但不太确定这些解决方案。 I tried something like the following but found it was of no use.
我尝试了类似下面的东西,但发现它没有用。
What I want to happen is if the user fills out the form and decides to clear the form, once they click 'Clear Form', the form should reset.我想要发生的是,如果用户填写表格并决定清除表格,一旦他们点击“清除表格”,表格应该重置。 All the fields need to be blank again.
所有字段都需要再次留空。
handleClearForm(){
this.setState({
decisionDate: '',
Veggies:'',
fullName:'',
comment:''
})
}
How can I clear a form in react?如何清除反应中的表格? Any help would be much appreciated.
任何帮助将非常感激。
Check this improved code检查这个改进的代码
class App extends React.Component{
constructor(){
super()
this.state = {
decisionDate: '',
Veggies:'',
fullName:'',
comment:''
}
}
setdecisionDateValue (value) {
this.setState({
decisionDate: value
})
}
componentDidMount(){
$( "#decisionDate" ).datepicker({
onSelect: this.setdecisionDateValue
});
}
handleClearForm = () => {
this.setState({
decisionDate: '',
Veggies:'',
fullName:'',
comment:''
})
}
handleChange = (e) => {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({[name]: value})
}
render(){
const { decisionDate,Veggies,fullName,comment} = this.state;
return(
<div>
<input type="text" name="fullName"
placeholder="Full Name"
onChange={this.handleChange}
value={fullName}/><br /><br />
<input type="text"
name="decisionDate"
id="decisionDate"
onChange={this.handleChange}
placeholder="MM/DD/YYYY"
value={this.state.decisionDate} /><br /><br />
<textarea name="comment"
value={comment}
onChange={this.handleChange}/><br /><br />
<input
type="checkbox"
name="Veggies"
onChange={this.handleChange}
checked={Veggies}
/>Veggies<br /><br />
<button onClick={this.handleClearForm}>
Clear Form
</button>
</div>
)
}
}
ReactDOM.render(
<App />,
document.getElementById("root")
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.