У меня есть модальный ремешок, который используется для бронирования встреч, которые хранятся в базе данных sql. Вот модальный компонент:
import React from 'react';
import { Button, Modal, ModalHeader, ModalBody, ModalFooter, Col, Form, FormGroup, Label, Input, Container,Alert } from 'reactstrap';
import Request from './Request.js'
class Appointment extends React.Component {
constructor(props) {
super(props);
this.state = {
modal: false,
Date: null,
description: ""
};
this.toggle = this.toggle.bind(this);
this.bookMeeting = this.bookMeeting.bind(this);
this.handleEvent = this.handleEvent.bind(this);
}
toggle() {
this.setState(prevState => ({
modal: !prevState.modal
}));
}
bookMeeting(){
console.info("subtmit!")
if (this.state.Date != null && this.state.description != "")
{
let date = this.state.Date
let desc = this.state.description
const requestBody = {
date: date,
description:desc
}
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
Request.post("http://localhost:4000/bookAppointment",requestBody,config)
.then((results) => console.info(results))
.catch(err => console.info(err))
}
}
handleEvent(event){
var key = event.target.id
var val= event.target.value
console.info([key] + ":" + val)
this.setState({[key]:val})
}
render() {
return (
<div>
<Button color = "danger" onClick = {this.toggle}>{this.props.buttonLabel}</Button>
<Modal isOpen = {this.state.modal} toggle = {this.toggle} className = {this.props.className}>
<ModalHeader toggle = {this.toggle}>Set up a meeting</ModalHeader>
<ModalBody>
<article> Here you can set up a meeting with your partner. Just provide a date and a time and a small description of the meeting! We'll keep track of it for you and remind you when its coming up!</article>
<hr/>
<div>
<Form>
<FormGroup>
<Label for = "Date">Date:</Label>
<Input type = "Date" id = "Date" name = "Date"onChange = {this.handleEvent}/>
</FormGroup>
<FormGroup>
<Label for = "description">Description:</Label>
<Input type = "textarea" id = "description" name = "description"onChange = {this.handleEvent}/>
</FormGroup>
</Form>
</div>
</ModalBody>
<ModalFooter>
<Button color = "primary" type = "button" onClick = {this.bookMeeting()}>Book Meeting</Button>
<Button color = "secondary" onClick = {this.toggle}>Cancel</Button>
</ModalFooter>
</Modal>
</div>
);
}
}
export default Appointment;
Всякий раз, когда я меняю какие-либо поля ввода, вызывается bookMeeting(). Я использовал аналогичную структуру получения входных данных и отправки их в свой API для страницы входа и регистрации и раньше не сталкивался с подобными проблемами. Даже нажатие кнопки для запуска модального окна вызывает вызов функции bookMeeting().



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Проблема на линии <Button color = "primary" type = "button" onClick = {this.bookMeeting()}>Book Meeting</Button>
Вместо того, чтобы инициализировать его в onClick, вы фактически вызываете функцию здесь. Простое изменение этой строки на <Button color = "primary" type = "button" onClick = {this.bookMeeting}>Book Meeting</Button> решит проблему здесь. В остальных местах вы правильно написали. onClick = {this.bookMeeting} необходимо выполнить.