【问题标题】:react-modal: How to close one modal and open a new one at the same time?react-modal:如何关闭一个模式并同时打开一个新模式?
【发布时间】:2019-05-06 01:30:37
【问题描述】:

我想实现像 Airbnb/Medium 这样的身份验证模式。当我在登录模式中单击“注册”时,登录模式关闭,注册模式打开。我阅读了 react-modal 文档,但没有看到这样做的方法。谁能帮助我找到解决方案。谢谢。

【问题讨论】:

  • 您好,很高兴看到您已经实现的一些代码。除此之外,我会建议一个容器组件,您可以在其中根据状态渲染这两个模式(例如 showLoginModal、showRegisterModal)。您可以通过在组件的 onClick 中使用回调函数来设置它。

标签: reactjs react-modal


【解决方案1】:

我不使用 React Modal,但我知道实现它的方法。这个想法是将您的注册和登录组件包装在存储模式状态和打开/关闭方法的父组件中。然后可以将这些方法作为 props 传递给子组件。

代码示例:

import React, { Component } from "react";
import ReactDOM from "react-dom";
import Modal from "react-modal";

class ModelWrapper extends Component {
  state = {
    loginOpened: false,
    signupOpened: false
  };
  openModal = modalType => () => {
    if (modalType === "login") {
      this.setState({
        loginOpened: true,
        signupOpened: false
      });
    } else if (modalType === "signup") {
      this.setState({
        loginOpened: false,
        signupOpened: true
      });
    }
  };
  closeModal = modalType => () => {
    if (modalType === "login") {
      this.setState({
        loginOpened: false
      });
    } else if (modalType === "signup") {
      this.setState({
        signupOpened: false
      });
    }
  };
  render() {
    const { loginOpened, signupOpened } = this.state;
    return (
      <>
        <Modal isOpen={loginOpened} onRequestClose={this.closeModal("login")}>
          <h1>Login</h1>
          <button onClick={this.openModal("signup")}>Open Signup</button>
          <button onClick={this.closeModal("login")}>Close this modal</button>
        </Modal>
        <Modal isOpen={signupOpened} onRequestClose={this.closeModal("signup")}>
          <h1>Sign Up</h1>
          <button onClick={this.openModal("login")}>Open Login</button>
          <button onClick={this.closeModal("signup")}>Close this modal</button>
        </Modal>
        <button onClick={this.openModal("login")}>Open Login</button>
        <button onClick={this.openModal("signup")}>Open Signup</button>
      </>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<ModelWrapper />, rootElement);

查看实际操作:https://codesandbox.io/s/q86lwklnxj

【讨论】:

  • 谢谢。这是否也适用于多个模态,对吗?
  • 它可以工作,但是您需要一种更好的方式来管理状态。如果有帮助,请点赞并接受这个答案。谢谢!
  • 这个答案似乎假设您需要在 openModal 和 closeModal 方法中注册任何新模式。这不是一个好主意。如果你有20个怎么办?顺便说一句,这打破了 SOLID 开/关原则。当然,您可以将其自动化并说“当一个新的打开时,循环遍历其余的模态并在需要时关闭它们”。但是,您仍然必须在列表中注册任何新模式。
  • @mayid 这是一个很好的观点。实际上还没有想到更好的解决方案,但一种天真的方法是使用数组并传递可用于设置状态的模态索引
  • 我今天尝试了一些东西......将引用分配给模态,并将它们存储在 Map 中(使用引用作为键,关闭方法作为关闭值)。然后,循环地图并关闭除当前模式之外的任何内容。然而,我被卡住了。现在我正在尝试使用上下文,但我找不到只渲染一次 ReactModal 的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-14
  • 2022-11-01
  • 1970-01-01
  • 2021-02-03
  • 1970-01-01
  • 1970-01-01
  • 2021-09-30
相关资源
最近更新 更多