只是为了开始这个,我正在从头开始学习,所以请保持谦虚。我已经尝试了几天来解决这个问题,这是我的最后选择(我想尝试自己尝试一下)。
我在Reactstrap模态中有以下代码(只是相关部分):
Modal.js
const { toggle, onSave } = this.props;
return (
<ModalBody>
<AvForm>
<AvGroup>
<Label for="description">Description</Label>
<AvInput
type="text"
name="description"
value={this.state.activeItem.description}
onChange={this.handleChange}
placeholder="Tool description"
required
/>
<AvFeedback valid>
Looking good
</AvFeedback>
<AvFeedback>
Uh oh! Looks like a blank string
</AvFeedback>
and a button:
<Button onClick={() => onSave(this.state.activeItem)}>
Save
</Button>
</AvForm>
</ModalBody>
App.js(我想还是相关部分)
toggle = () => {
this.setState({ modal: !this.state.modal });
};
handleSubmit = item => {
this.toggle();
if (item.id) {
axios
.put(`http://localhost:8000/api/todos/${item.id}/`, item)
.then(res => this.refreshList());
return;
}
axios
.post("http://localhost:8000/api/todos/", item)
.then(res => this.refreshList());
};
render() {
return(
...
{this.state.modal ? (
<Modal
activeItem={this.state.activeItem}
toggle={this.toggle}
onSave={this.handleSubmit}
/>
) : null}
...
如果删除onClick事件,则表单验证将按您期望的方式工作。我只是不确定如何告诉它首先执行验证,如果通过了,那就继续提交,否则显示验证警告并保持表单打开...
非常感谢您的帮助!
尝试使用AvForm的onValidSubmit。根据文档,仅当提交时每个字段均有效时才调用此回调:
handleSubmit(){
onSave(this.state.activeItem)
}
<AvForm onValidSubmit={this.handleSubmit}>
...
</AvForm>