用Submit关闭React Modal

时间:2019-05-01 16:13:21

标签: reactjs react-modal

您好,我正在尝试找出如何关闭此模式并同时提交新项目的方法。。。现在它只在做另一个。如果我将<button onClick={this.handleCloseModal}>Submit</button>放在底部,它将不会以表单的形式提交信息;如果我删除了{this.handleCloseModal},它将添加该项目,但我必须刷新以关闭模式。

class AddItem extends React.Component {
	constructor() {
		super();
		this.state = {
			showModal: false
		};

		this.handleOpenModal = this.handleOpenModal.bind(this);
    	this.handleCloseModal = this.handleCloseModal.bind(this);
  	}
  
  		handleOpenModal () {
    	this.setState({ showModal: true });
  	}
  
  		handleCloseModal () {
    	this.setState({ showModal: false });
  	}


	render() {
		return(
		<div>
		<button onClick={this.handleOpenModal}>Add Item</button>
		<ReactModal isOpen={this.state.showModal}>
		<form 
			onSubmit={(event) => {
				event.preventDefault()

				const input = {
					name: event.target.itemName.value,
					price: event.target.itemPrice.value,
					description: event.target.itemDescription.value, 
					userEmail: this.props.currentUser.email
			}

				this.props.dispatch(saveItem(input))
		
				event.target.itemName.value = ''
				event.target.itemPrice.value = ''
				event.target.itemDescription.value = ''
		
			}}>
				<label>
					Item Name:
					<br />
					<input type="text" name="itemName" validate={[required, nonEmpty]} />
				</label>
				<br />
				<label>
					Price:
					<br />
					<input type="text" name="itemPrice" validate={[required, nonEmpty]} />
				</label>
				<br />
				
				<br />
				<label>
				Description:
					<br />
					<textarea type="text" name="itemDescription" validate={[required, nonEmpty]} />
				</label>
				<br />
				<button onClick={this.handleCloseModal}>Submit</button>
			</form>
			</ReactModal>
			</div>
		)
	}
}

const mapStateToProps = state => ({
    currentUser: state.auth.currentUser
});
	
	export default withRouter(connect(mapStateToProps)(AddItem));

1 个答案:

答案 0 :(得分:0)

您可以使用函数处理程序来提交表单,然后最后关闭模式。

handleOnSubmit(event) {
    event.preventDefault()

    const input = {
        name: event.target.itemName.value,
        price: event.target.itemPrice.value,
        description: event.target.itemDescription.value, 
        userEmail: this.props.currentUser.email
    }

    this.props.dispatch(saveItem(input))

    event.target.itemName.value = ''
    event.target.itemPrice.value = ''
    event.target.itemDescription.value = ''

    this.handleCloseModal(); <--- you can place it right here
}

该按钮将用于触发传递到表单的onSubmit函数:

<form onSubmit={this.handleOnSubmit}>
.
.
.
</form>

// Here the button will use the form onSubmit by default
// Hence, handleOnSubmit will be called
<button type="submit">Submit</button>

别忘了绑定handleOnSubmit