Как добавить переход при закрытии модального в React и как закрыть при нажатии за пределами модального? - PullRequest
0 голосов
/ 15 апреля 2020

Я знаю, что есть много разных вопросов. Я проверил их, но так и не смог найти способ их решить. Пришлось спросить это, потому что я застрял и не мог никуда двигаться. Я новый ученик и все еще новичок в React и пытаюсь внедрить модалы в моем проекте Здесь возникает два вопроса.

  1. Как добавить переход при закрытии?

Как только пользователь нажимает на карточки, я показываю модал с переходом, но когда пользователь закрывается, я не могу применить переход для некоторая причина.

Я изменяю метод на открытом или закрытом модальном режиме и делаю переход в css со следующим кодом:

.show .modal-parent {
  animation-name: zoom;
  animation-duration: 0.6s;
}

@-webkit-keyframes zoom {
    from {-webkit-transform:scale(0)} 
    to {-webkit-transform:scale(1)}
  }

  @keyframes zoom {
    from {transform:scale(0)} 
    to {transform:scale(1)}
  }   

Всякий раз, когда пользователь нажимает карты, я показываю класс .show и применяю переход на .modal-parent, где лежит весь мой модальный контент. Теперь я хотел бы сделать то же самое, когда пользователь закрывает модальное окно.

Как бы я закрыл модальный при щелчке снаружи?

Приложение. js файл находится здесь:

import React from "react";
import "./App.css";
import Cards from "./components/Cards/cards.js";
import users from "./employees.json";
import Navbar from "./components/Navbar";
import Modals from "./components/Modals";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      index: 0,
      open: false,
    };
    this.nextPerson = this.nextPerson.bind(this);
  }

  userIndex = (cardIndex) => {
    this.setState({
      index: cardIndex,
      open: true,
    });
  };

  nextPerson = () => {
    this.setState({
      index: this.state.index + 1,
    });
  };
  previousPerson = () => {
    this.setState({
      index: this.state.index - 1,
    });
  };
  close = () => {
      this.setState({
        open: false,
      });

  };
  render() {
    let person = users[this.state.index];

    return (
      <div className="container">
        <Navbar />
        <div className="team-text"><p> Our team of <span className="team-number">42</span> strategists, designers, engineers, developers and managers<br/>make custom products for startups and leading companies. </p> </div>
        <div className="top-card">
          {users.map((user) => {
            return (
              <Cards
                user={user}
                users={users}
                key={user.id}
                userIndex={this.userIndex}
              />
            );
          })}
          <Modals
            open={this.state.open}
            users={users}
          >
            <div class="modal-parent">
              <div className={`modal-nav ${person.department === "Engineering" ? "engineer" : ""} ${person.department === "Business" ? "business" : ""}${person.department === "Design" ? "design" : ""}`}>
                <div className="modal-close">
                  <a
                    href="#close"
                    title="Close"
                    className="close"
                    type="button"
                    onClick={this.close}
                  >
                    Close
                  </a>
                </div>{" "}
              </div>

              <div className="modal-image">
                <img src={person.avatar} alt="" class="modal-avatar"></img>{" "}
              </div>
              <div> </div>
              <div className="modal-info">
                <h1 className="modal-name">
                  {person.firstName} {person.lastName}
                </h1>
                <h5 className="modal-title">{person.jobTitle}</h5>
                <h5 className="modal-department">{person.department}</h5>
              </div>
              <div className="modal-bio">
                <p>{person.bio}</p>
              </div>
              <div className="modal-contacts">
                <a href={`mailto: ${person.contact.phone}`}>
                  <span className={`material-icons phone ${person.department === "Engineering" ? "engineer" : ""} ${person.department === "Business" ? "business" : ""}${person.department === "Design" ? "design" : ""}`}>call</span><span className="contact-text">{person.contact.phone}</span>
                </a>{" "}
                <a href={`mailto: ${person.contact.email}`}>
                  <span className={`material-icons email ${person.department === "Engineering" ? "engineer" : ""} ${person.department === "Business" ? "business" : ""}${person.department === "Design" ? "design" : ""}`}>email</span><span className="contact-text">{person.contact.email}</span>
                </a>{" "}
                <a href={person.contact.url}>
                  <span className={`material-icons computer ${person.department === "Engineering" ? "engineer" : ""} ${person.department === "Business" ? "business" : ""}${person.department === "Design" ? "design" : ""}`}>computer</span><span className="contact-text">{person.contact.url}</span>
                </a>{" "}
              </div>
              <div className="modal-previous-btn">
                <button
                  className="previous-button"
                  onClick={this.previousPerson}
                  disabled={this.state.index <= 0 ? true : false}
                >Previous
                </button>
              </div>
              <div className={`modal-next-btn ${person.department === "Engineering" ? "engineer" : ""} ${person.department === "Business" ? "business" : ""}${person.department === "Design" ? "design" : ""}`}>
                <button
                  className="next-button"
                  onClick={this.nextPerson}
                  disabled={this.state.index >= 41 ? true : false}
                >Next
                </button>
              </div>
            </div>
          </Modals>
        </div>
      </div>
    );
  }
}

export default App;


1 Ответ

1 голос
/ 15 апреля 2020

Чтобы закрыть модальное окно, когда вы щелкаете мышью снаружи, вам нужно изменить компонент модального окна. Сначала вы создаете ссылку в начале:

modalRef = React.createRef();

Затем вы используете эту ссылку в функции рендеринга:

return (
  <div ref={this.modalRef}...

Вы слушаете события mousedown во время жизни вашего модального компонента:

componentDidMount() {
    document.addEventListener("mousedown", this.handleMouseDown);
}

componentWillUnmount() {
    document.removeEventListener("mousedown", this.handleMouseDown);
}

И вы проверяете, был ли щелчок за пределами ссылки в обработчике:

// Mouse click event, if outside of the popup then close it
handleMouseDown= (event) => {
    if (!this.modalRef.current.contains(event.target)) {
      // Notify the parent with a callback to hide the modal
    };
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...