![](/img/trans.png)
[英]What is the proper way to test a form with a lot of input fields using Jest and react-testing-library?
[英]What is the proper way to clear a React Form?
我有一个表单,其中包含一些使用 Reactjs 创建的不同类型的元素(文本框、复选框等)。我一直很难弄清楚如何清除表单。 我在谷歌上搜索过,但不太确定这些解决方案。 我尝试了类似下面的东西,但发现它没有用。
我想要发生的是,如果用户填写表格并决定清除表格,一旦他们点击“清除表格”,表格应该重置。 所有字段都需要再次留空。
handleClearForm(){
this.setState({
decisionDate: '',
Veggies:'',
fullName:'',
comment:''
})
}
如何清除反应中的表格? 任何帮助将非常感激。
检查这个改进的代码
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.