问题
I want to implement an authentication modal like Airbnb/Medium. When I click "Sign Up" in the Login Modal, The Login Modal closes and the Register Modal opens. I read react-modal docs and didn't see a way to do so. Could anyone please assist me finding a solution. Thanks.
回答1:
I don't use React Modal, but I know a way of implementing it. The idea is to wrap your Sign Up and Login components inside a parent component that stores the modals' state and open/close methods. These methods can then be passed down as props to the children components.
Code example:
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);
See it in action: https://codesandbox.io/s/q86lwklnxj
来源:https://stackoverflow.com/questions/53616045/react-modal-how-to-close-one-modal-and-open-a-new-one-at-the-same-time