输入字段仍保存数据

时间:2019-08-25 18:21:19

标签: reactjs bootstrap-4

我是新来的。我有一个子组件,并且在模态中有一个输入字段。我在父组件中有状态。提交值后,该值仍保留在输入中。我该如何克服这个问题?

这是我在父类中的状态和处理程序:

state = {
        unitName: ''
    }

    inuptChangeHandler = (event) => {
        event.preventDefault();
        this.setState({ [event.target.name]: event.target.value })
    }
postUnitHandler = () => {
        let unit = {
            unitName : this.state.unitName
        }
        Axios.post('http://localhost:4000/addUnit',unit).then(response => {
            console.log("unit added")

        }).catch(err => {
            console.log(err);
        })
        this.setState({ unitName: ''})

    }

子组件的用法:

 <AddUnit changeInput={this.inuptChangeHandler}
           addUnit={this.postUnitHandler} />

子组件

<div className="modal-body">
<form>
<div className="form-group">
<label className="text-dark" htmlFor="unit"><strong>Add Unit</strong></label>
<input type="text"  className="form-control" name="unitName"  onChange={props.changeInput} placeholder="Enter New Unit" />
</div>
</form>
</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" className="btn btn-primary" data-dismiss="modal" onClick={props.addUnit}>Save changes</button>
</div>

每次我按下“提交”时,输入字段应该为空

1 个答案:

答案 0 :(得分:2)

将prop unitName传递给子组件,然后在输入标签中使用value = {unitName}

<input type="text"  className="form-control" name="unitName"  value={unitName} onChange={props.changeInput} placeholder="Enter New Unit" />

unitName应该是父组件中的状态,应该传递给子组件