谁能告诉我在我的主页组件上单击提交后如何清除所有输入?我尝试在subjectForm组件中的preventdefault之后使用reset(),但要么使用错误,要么不起作用。我还尝试使用setState并将输入恢复到默认状态,默认状态为空,但也不起作用。
代码中的所有内容都很好,但每次我提交主题时,字段本身都不清楚
这是我的主页组件。
import React from 'react';
import SubjectForm from './SubjectForm';
import {addSubject} from '../actions/subjectAction';
import {connect} from 'react-redux';
const HomePage=({dispatch})=>(
<div>
<SubjectForm onSubmit ={(subject)=>
dispatch(addSubject(subject))
}/>
</div>
)
export default connect()(HomePage);
这是我的subjectForm组件
import React from 'react';
export default class SubjectForm extends React.Component{
constructor(props){
super(props);
this.state={...}
onNameChange =(e)=>{...}
onHourChange =(e)=>{...}
onSubmit=(e)=>{
e.preventDefault();
**//I tried using reset() here but it did not work**
if(!this.state.subjectName){...}
render(){
return (
<div>
{this.state.error && <p>{this.state.error}</p>}
<form className='test' onSubmit={this.onSubmit}>
<input
type="text"
placeholder='enter name'
autoFocus
value={this.state.subjectName}
onChange={this.onNameChange}
/>
<input
type="number"
placeholder='enter hour'
value={this.state.hour}
onChange={this.onHourChange}
/>
<button>Add Subject</button>
</form>
</div>
)
}
}
这是我试图将subject返回为空时的onSubmit函数。
onSubmit=(e)=>{
e.preventDefault();
if(!this.state.subjectName){
this.setState(()=>({error:'please enter subject name'}))
}
else if(!this.state.hour && !this.state.minute){
this.setState(()=>({error:'please enter time'}))
}else {
this.setState(()=>({error:''}));
this.props.onSubmit({
subjectName:this.state.subjectName,
hour:this.state.hour,
minute:this.state.minute,
note:this.state.note
}, console.log(this.state),
)
this.setState(()=>({
subjectName:'',
hour:0,
minute:0,
note:'',
error:''
}));
}
}