博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[React] Create a Query Parameter Modal Route with React Router
阅读量:4983 次
发布时间:2019-06-12

本文共 1996 字,大约阅读时间需要 6 分钟。

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':

    
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(      
{this.props.children}
, 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 = (  
);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") && (        
{ this.props.history.push(this.props.location.pathname); }} >
Login modal
) ); }}

 

Using:

Login

 

转载于:https://www.cnblogs.com/Answer1215/p/11299654.html

你可能感兴趣的文章
LVS _keepalived 配置
查看>>
Django之ORM基础
查看>>
JS监听浏览器关闭事件
查看>>
[Log]ASP.NET之HttpModule 事件执行顺序
查看>>
明天回老家看我儿子了!
查看>>
hdu2089(数位dp模版)
查看>>
JS 获取浏览器和屏幕宽高信息
查看>>
TCP/UDP 协议,和 HTTP、FTP、SMTP,区别及应用场景
查看>>
我的大学生活
查看>>
php SPL四种常用的数据结构
查看>>
计算tableview的高度
查看>>
使用外语会影响我们的道德判断
查看>>
菜鸟学Java第一天
查看>>
【freemaker】之自定义指令通用select模版
查看>>
PHP类和对象之重载
查看>>
解决 win10 由于磁盘缓慢造成机器迟钝
查看>>
flask-信号
查看>>
Spring-Cloud的版本是如何定义的
查看>>
传入class、id name 的函数封装
查看>>
软工网络15团队作业3——需求分析与设计
查看>>