在我的案例中单击提交后如何清除反应中的输入字段?

how can I clear input field in react after click submit in my case?

谁能告诉我在主页组件上单击提交后如何清除所有输入?我尝试在 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> 
        )
    }
}

这是我尝试 return 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:''
        }));
    }
}

由于您正在使用您的状态来控制输入字段,因此您应该重置 state.field,它会重置该字段。所以:

onSubmit=(e)=>{
    e.preventDefault();

    **//I tried using reset() here but it did not work**

    if(!this.state.subjectName){...}

    // after finishing all you want to do with it:
    this.setState({
        hour: '', // or any other initial value you have
        subjectName: '',
    });
}