react-modal:如何关闭一个模态并同时打开一个新模态?

react-modal: How to close one modal and open a new one at the same time?

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

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

代码示例:

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