我有一个反应表。用户填写表单并提交表单,但是提交时出现错误。显示错误。当用户点击重置按钮时,我希望该错误消失。我怎么做?因此,一旦用户重置了表单,我希望表单是新的。我已经包含了所有代码。
这是我的代码:
class VehiclePage extends React.Component{
defaultState = { errors: [], tag: null, vin: null, location: null, message:
null, msg: null};
constructor(props){
super(props);
this.state=this.defaultState;
this.submitVehicle=this.submitVehicle.bind(this);
this.resetFromState=this.resetFromState.bind(this);
this.validateForm = this.validateForm.bind(this);
}
resetFromState= ()=>{
this.setState({
...this.defaultState});
}
validateForm(tag, vin, location){
const errors=[];
if (tag==''){
errors.push("Please enter vehicle's RFIDTAG.");
}else if (vin==''){
errors.push("Please enter the vehicle's VIN.");
}else if(vin.length<17){
errors.push("VIN must be longer than 17 characters.");
}else if(location==''){
errors.push("Please enter vehicle's location.");
}
return errors;
}
submitVehicle(tag, vin, location){
let msg;
let errors=this.validateForm(tag, vin, location);
console.log("tag:", tag);
if(errors.length>0){
this.setState({errors: errors});
console.log("error: ", errors);
return;
}else{
this.setState({errors: []});
var input={
rfidtag: tag,
vin: vin,
vehzone: location
};
console.log("the object is: ", input);
this.props.createVehicle(input);
if(this.props.message != ''){
console.log("SERVER ERROR!!!");
}
}
}
render(){
const {errors} = this.state;
return(
<div>
<AddVehicle submitVehicle={this.submitVehicle}
resetFromState={this.resetFromState} />
<div><font color="red">{errors}</font></div>
<h4>{this.props.message}</h4>
</div>
)
}
}
const mapStateToProps=(state, ownProps) => {
console.log("state in vehicle page is: ",state);
return{
vehicle: state.vehicle,
message: state.vehicleReducer.message,
error: state.vehicleReducer.error
}
};
const mapDispatchToProps=(dispatch)=>{
return {
createVehicle: vehicle =>
dispatch(vehicleActions.createVehicle(vehicle))
}
};
export default connect(mapStateToProps, mapDispatchToProps)(VehiclePage);
答案 0 :(得分:0)
要重置表单,您需要向value
之类的元素中添加input
属性
<input value={this.state.formValue1} ...>
然后,当您要重置它们时,将它们重新设置为默认值
this.setState({ formValue1: "", formValue2: "" });
答案 1 :(得分:0)
弄清楚如何做。我创建了一个名为reset的动作,并在按下reset按钮时调用了它。