我在handleChange函数中尝试了几种不同的方法,但我总是记录{this.state.crup}被设置为构造函数中设置的空字符串。我也不确定";name";prop在我的input标记中是必要的,或者如果我应该在handleChange函数中使用它。非常感谢您的帮助!
constructor(props) {
super(props);
this.state = {
isOpen: false,
crust: ""
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
openModal = () => this.setState({ isOpen: true });
closeModal = () => this.setState({ isOpen: false });
handleCloseModal = () => {
this.setState({
isOpen: false
});
};
handleSubmit = (event) => {
event.preventDefault();
this.setState({
isOpen: true
});
};
handleChange(event) {
this.setState({ [event.target.name]: event.target.value });
}
render() {
return (
<div className = "form-box">
<h5 className = "form-step"> Enter your order below </h5>
<br />
<form onSubmit={this.handleSubmit}>
<div className = "field1">
<label>
Crust :
<input
type="text"
name={this.props.crust}
defaultValue={this.state.crust}
onChange={this.handleChange}
ref={node => (this.inputNode = node)}
/>
</label>
<br />
</div>
<button type="submit" className="submitBtn" onClick={this.openModal}>Submit</button>
<Modal
show={this.state.isOpen}
onHide={this.closeModal}
size="lg"
aria-labelledby="contained-modal-title-vcenter"
centered
>
<Modal.Header closeButton>
<Modal.Title id="contained-modal-title-vcenter">
Thank you for ordering with us, here is what you got!
</Modal.Title>
</Modal.Header>
<Modal.Body>
<p id="order">
{this.state.crust}
</p>
</Modal.Body>
</Modal>
</form>
</div>
)
}
}
您必须将value
传递给输入:
<input
type="text"
name={this.props.crust}
value={this.state.crust}
onChange={this.handleChange}
ref={node => (this.inputNode = node)}
/>
没有关于输入名称的最佳实践,您可以像以前一样保留它。
我通过采取"地壳;从我的构造函数中删除。我认为构造函数不允许this.state.crust的值从空字符串更改。