0

您好,我正在尝试弄清楚如何关闭此模式并同时提交一个新项目......现在它只做一个或另一个。如果我把它放在<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));

4

1 回答 1

2

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

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

于 2019-05-01T16:56:24.807 回答