Close React Модальный - PullRequest
       23

Close React Модальный

0 голосов
/ 24 апреля 2019

У меня много проблем, когда я пытаюсь выяснить, как добавить работающую кнопку закрытия в мой модал - конструктор / props не работает, и я не уверен, что ставить после onClick = в элементе button .

class Modal extends React.Component {

// whenever component gets rendered to the screen we create a new div assigned to this.modalTarget
	componentDidMount() {
		this.modalTarget = document.createElement('div');
		// add class name to modal target
		this.modalTarget.className = 'modal';
		// take the div we just created and append it to the body tag in doc
		document.body.appendChild(this.modalTarget);
		// call method _render
		this._render();
	}

// whenever the component's about to update we do another render
// this render makes sure that if we get a new set of components or children in the modal
// we're going to render those to the parent div as well
	componentWillUpdate() {
		this._render();
	}

// clean up - whenever the component is about to unmount from the screen
// cleans up dom when the modal is removed from the component heirarchy
	componentWillUnmount() {
		// unmounts this.props.children
		ReactDOM.unmountComponentAtNode(this.modalTarget);
		document.body.removeChild(this.modalTarget);
	}

	_render() {
		// take react dom library and render a div that contains this.props.children
		// and render it into this.modalTarget
		ReactDOM.render(
			<Provider store= {store}>
				<Router>
					<div className="modal">
						{this.props.children}
						<button>Close</button>
					</div>
				</Router>
			</Provider>,
			this.modalTarget

Ответы [ 2 ]

1 голос
/ 25 апреля 2019

Несколько вопросов здесь.Во-первых, отойдите от прямого манипулирования DOM.React использует виртуальный DOM, поэтому вам не нужно вручную добавлять или удалять DOM элементы.React автоматически обрабатывает эту DOM манипуляцию с помощью метода render.Кроме того, вам нужно будет управлять этим Modal, используя какой-то state (isOpen).Это может быть через локальное состояние React или через состояние Redux.В любом случае, его нужно контролировать и сравнивать.Проще говоря, если он открыт, то визуализируйте Modal, если он закрыт, то визуализируйте null.

Кроме того, этот компонент Modal может быть структурирован для повторного использования.Просто добавьте его как child к другому parent компоненту с состоянием и включите в него все, что вы хотите визуализировать children.

Рабочий пример :

Edit Simple Modal


компоненты / Example.js (родительский компонент)

import React, { Component } from "react";
import Modal from "../Modal";
import "./styles.css";

class Example extends Component {
  state = { isOpen: false };

  handleOpenModal = () => {
    this.setState({ isOpen: true });
  };

  handleCloseModal = () => {
    this.setState({ isOpen: false });
  };

  render = () => (
    <div className="example">
      <h2>Simple Modal Example</h2>
      <button
        className="uk-button uk-button-primary uk-button-small"
        onClick={this.handleOpenModal}
      >
        Open Modal
      </button>
      <Modal isOpen={this.state.isOpen} onCloseModal={this.handleCloseModal}>
        <h1 className="title">Hello!</h1>
        <p className="subtitle">There are two ways to close this modal</p>
        <ul>
          <li>Click outside of this modal in the grey overlay area.</li>
          <li>Click the close button below.</li>
        </ul>
        <button
          className="uk-button uk-button-danger uk-button-small"
          onClick={this.handleCloseModal}
        >
          Close
        </button>
      </Modal>
    </div>
  );
}

export default Example;

компоненты / Modal.js (дочерний компонент - он содержит множество более мелких компонентов, которые были разделены для повторного использования и простоты понимания - они в основном простые div с некоторыми styles прикрепленными - см. Примечания ниже)

import React from "react";
import PropTypes from "prop-types";
import BackgroundOverlay from "../BackgroundOverlay"; // grey background
import ClickHandler from "../ClickHandler"; // handles clicks outside of the modal
import Container from "../Container"; // contains the modal and background
import Content from "../Content"; // renders the "children" placed inside of <Modal>...</Modal>
import ModalContainer from "../ModalContainer"; // places the modal in the center of the page

// this is a ternary operator (shorthand for "if/else" -- if cond ? then : else)
// below can be read like: if isOpen is true, then return/render the modal, else return null
const Modal = ({ children, isOpen, onCloseModal }) =>
  isOpen ? (
    <Container>
      <BackgroundOverlay />
      <ModalContainer>
        <ClickHandler isOpen={isOpen} closeModal={onCloseModal}>
          <Content>{children}</Content>
        </ClickHandler>
      </ModalContainer>
    </Container>
  ) : null;

// these proptype declarations are to ensure that passed down props are 
// consistent and are defined as expected
Modal.propTypes = {
  children: PropTypes.node.isRequired, // children must be a React node
  isOpen: PropTypes.bool.isRequired, // isOpen must be a boolean
  onCloseModal: PropTypes.func.isRequired // onCloseModal must be a function
};

export default Modal;
0 голосов
/ 24 апреля 2019

Похоже, ваш модал открыт только на основе того, отображается ли он родителем. Если не считать всего вместе реструктуризации этого шаблона, единственный способ достичь того, что вы хотите, - это передать какой-то обратный вызов onClose:

class Parent extends React.Component {
  state = { isModalOpen: false };

  render() {
    return (<div>
      // Stuff
      {this.state.isModalOpen &&
        <Modal onClose={() => this.setState({ isModalOpen: false })}/>
      }
      // Stuff
    </div>);
  }
}

В вашем Modal:

<div className="modal">
    {this.props.children}
    <button onClick={this.props.onClose}>Close</button>
</div>
...