如何从Modal, Form使用react和bootstrap发送数据?



我正在使用React到本地数据库中的POST数据。当我只用<form>时,它工作得很好。但每当我试图使用模态和引导,它给我一个错误。我知道我的handleChange/handleSubmit可能没有分配值。只是想知道如何将数据从Modal发送到handleChange

下面是我的代码:
constructor(props) {
super(props);
this.state = {
institutionName: {},
institutionAddress: {},
institutionPhone: {},
allData: [],
};
this.onSubmit = this.handleSubmit.bind(this);
}
// this will look at the API and save the incoming data in allData variable
componentDidMount() {
fetch("/manageInstitution")
.then((res) => res.json())
.then((data) => this.setState({ allData: data }))
.then(console.log(this.state.allData));
}
// this is when submit button is pressed and data will be sent to database using api
handleSubmit(event) {
event.preventDefault();
const data = {
institutionName: this.state.institutionName,
institutionAddress: this.state.institutionAddress,
institutionPhone: this.state.institutionPhone,
};
fetch("/manageInstitution", {
method: "POST",
body: JSON.stringify(data),
headers: { "Content-Type": "application/json" },
})
.then((res) => res.json())
.catch((error) => console.error("Error: ", error))
.then((response) => console.log("Success: ", response));
window.location.reload(false);
}
// when a field changes in the form, do assignment to the state
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value.trim(),
});
};
handleModalShowHide() {
this.setState({ showHide: !this.state.showHide });
}
render() {
const { allData } = this.state;
return (
<div className="body">
<h4>Super Admin View</h4>
<div>
<Button variant="primary" onClick={() => this.handleModalShowHide()}>
Add New Institution
</Button>
<Modal
aria-labelledby="contained-modal-title-vcenter"
show={this.state.showHide}
onSubmit={this.handleSubmit}
>
<Modal.Header
closeButton
onClick={() => this.handleModalShowHide()}
>
<Modal.Title id="contained-modal-title-vcenter">
<h5>Add New Institution</h5>
</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form className="col-lg-6 offset-lg-3">
<Form.Group className="mb-3">
<Form.Label htmlFor="institutionName">
Institution Name:
</Form.Label>
<Form.Control
type="text"
size="sm"
name="institutionName"
placeholder="Enter Institution Name"
onChange={this.handleChange}
required
/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label htmlFor="institutionAddress">
Institution Address:
</Form.Label>
<Form.Control
type="text"
size="sm"
name="institutionAddress"
placeholder="Enter Institution Address"
onChange={this.handleChange}
required
/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label htmlFor="institutionPhone">
Institution Phone:
</Form.Label>
<Form.Control
type="tel"
size="sm"
name="institutionPhone"
placeholder="i.e 01911223344"
onChange={this.handleChange}
pattern="[0-9]{3}"
required
/>
</Form.Group>
</Form>
<Modal.Footer>
<Button
variant="secondary"
onClick={() => this.handleModalShowHide()} >Close </Button>
{"  "}
<Button
className="btn btn-primary"
type="submit"
onClick={this.handleSubmit}>Submit</Button>
</Modal.Footer>
</Modal.Body>
</Modal>
</div>
);
}
}
export default addNewInstitution;

错误如下:

TypeError: Cannot read properties of undefined (reading 'state')
handleSubmit
D:/eduBD-React/eduBD/client/src/components/superadmin/manageInstitution.jsx:30
27 |    event.preventDefault();
28 | 
29 |    const data = {
> 30 |      institutionName: this.state.institutionName,
31 |      institutionAddress: this.state.institutionAddress,
32 |      institutionPhone: this.state.institutionPhone,
33 |    };

您需要绑定或使用箭头函数来指向this正确的参考参考文档在这里

class App extends React.Component {
state = {
name: "hello"
};
handleChangeWithArrow = () => { // use this way to avoid such errors
console.log(this.state.name);
this.setState({ name: "helloo Im changed" });
};
handleChange() {
// need to bind this to work or use an arrow function
console.log(this.state.name);
this.setState({ name: "helloo Im changed" });
}
render() {
return (
<div>
<button onClick={this.handleChange}>Error Produced on Click</button>
<button onClick={this.handleChangeWithArrow}>
Click Me to change Name
</button>
{this.state.name}
</div>
);
}
}
ReactDOM.render(<App/>,document.querySelector('#root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

最新更新