标签:react Modal render Create React modal import
Routes are some times better served as a modal. If you have a modal (like a login modal) that needs to be routeable and appear on all pages you may need to use query params. Will explore how to render a route all the time and use query params to control when it's content renders.
Modal should be created as a 'Portal':
<body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> <div id="modal_root"></div> </body>
import React, { Component } from "react"; import { createPortal } from "react-dom"; const modalStyle = { position: "fixed", left: 0, top: 0, bottom: 0, right: 0, backgroundColor: "rgba(0,0,0,.2)", color: "#FFF", fontSize: "40px", }; export default class Modal extends Component { render() { return createPortal( <div style={modalStyle} onClick={this.props.onClick}> {this.props.children} </div>, document.getElementById("modal_root"), ); } }
If we want to show the Modal everywhere in the page, we need to declear the Router outside 'Switch' component:
import React from "react"; import ReactDOM from "react-dom"; import "./index.css"; import { BrowserRouter, Switch, Route } from "react-router-dom"; import HomePage from "./pages/home"; import ProfilePage from "./pages/profile"; import Login from "./pages/login"; const routes = ( <BrowserRouter> <Switch> <Route exact path="/" component={HomePage} /> <Route path="/profile" component={ProfilePage} /> </Switch> <Route path="/" component={Login} /> </BrowserRouter> ); ReactDOM.render(routes, document.getElementById("root"));
For all the routes re-render, Login component will be shown.
Inside Login componnet, control the component show / hide by query param:
import React, { Component } from "react"; import Modal from "./modal"; export default class LoginPage extends Component { render() { let params = new URLSearchParams(this.props.location.search); return ( params.get("login") && ( <Modal onClick={() => { this.props.history.push(this.props.location.pathname); }} > <div style={{ display: "flex", alignItems: "center", justifyContent: "center", height: "100%", }} > Login modal </div> </Modal> ) ); } }
Using:
<Link to={{ pathname: "/", search: "?login=true" }}>Login</Link>
标签:react,Modal,render,Create,React,modal,import 来源: https://www.cnblogs.com/Answer1215/p/11299654.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。