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

时间:2017-12-10 07:42:30

标签: reactjs components reset clear

有人可以告诉我如何在我的主页组件上点击提交后清除所有输入吗?我尝试在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:''
        }));
    }
}

1 个答案:

答案 0 :(得分:3)

由于您使用状态来控制输入字段,因此您应该重置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: '',
    });
}