博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
react 模态对话框_如何在React中渲染模态
阅读量:2531 次
发布时间:2019-05-11

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

react 模态对话框

Modals can be a tricky topic in React because of the way React structures the DOM. If you’re familiar with the basics of React, you will know that the entire App is a component, usually called <App/> that gets gets appended as a child <div> called #root. The index.html file looks like this:

由于React构造DOM的方式,模态在React中可能是一个棘手的话题。 如果您熟悉React的基础知识,您将知道整个App是一个组件,通常称为<App/> ,该组件将作为子<div>附加在#root后面。 index.html文件如下所示:

Once the <App/> Component gets rendered to the DOM, the actual <div> element with id “#root” gets the entire React App rendered inside it.

一旦<App/>组件被渲染到DOM,ID为“ #root”的实际<div>元素就会在其中渲染整个React App。

Consequently, it’s quite common that React App Components get very deeply nested. We are talking dozens of levels deep, and often more. So if one of those deeply nested Components needs to show a modal, it’s going to face some serious CSS issues.

因此,React App组件嵌套得很深很普遍。 我们正在谈论数十个层次,甚至更多。 因此,如果其中一个深层嵌套的组件之一需要显示模式,它将面临一些严重CSS问题。

Modals put an overlay on the screen, and therefore take a higher visual precedence over all other elements. If you had to put it in z-index terms, it would need to be the highest number of all the elements on screen. But since it is so deeply nested, the parent elements way up the tree take CSS precedence.

模态在屏幕上放置了覆盖层,因此比所有其他元素具有更高的视觉优先级。 如果必须使用z-index来表示,则它必须是屏幕上所有元素中的最高数量。 但由于它是如此深层的嵌套,因此树上的父元素优先于CSS。

Rather than touching the CSS which may be finely tuned, and so fiddling there could break the App, we need to find a way to render to the DOM — but outside of the deep nesting.

与其触摸可能经过微调CSS,以至于摆弄在那里可能会破坏App,我们需要找到一种方法来渲染DOM,但要在深层嵌套之外

解决方案— React门户 (Solution — React Portals)

One strategy is to use ReactDOM portals, and put the modal in a div that is a sibling component to the div with id “#root”. By doing so, the CSS styles applied to the modal’s div wrapper will apply only in relation to its sibling (the “#root” div), and that will not break the CSS styling of “#root”.

一种策略是使用ReactDOM门户,并将模式放在div中,该div是ID为“ #root”的div的同级组件。 这样,应用于模式的div包装器CSS样式将仅与其同级(“ #root” div)相关,并且不会破坏“ #root”CSS样式。

To do so we need to use the createPortal() method of ReactDOM. A portal is effectively such a sibling div, that bends the rule that all React components must be descendants of <div id=”root">. To do so we need to do the following:

为此,我们需要使用ReactDOM的createPortal()方法。 门户实际上是一个同级div,它打破了所有 React组件必须是<div id=”root">后代的规则,为此,我们需要执行以下操作:

  1. In index.html, inside the <body> tag:

    在index.html中的 <bod y>标记内:

    
. //ADD THIS

2. Create a Modal.js Component (classNames are from semantic-UI):

2.创建一个Modal.js组件( classNames来自语义UI ):

import React from "react";import ReactDOM from "react-dom";const JSX_MODAL = (  
THIS IS SOME TEXT IN THE MODAL // add some UI features here
);function Modal(props) { return ReactDOM.createPortal(JSX_MODAL, document.querySelector("#modal"));}export default Modal;

You will see that createPortal takes two arguments: some JSX that gets rendered, and similar to ReactDOM.render, the target element under which the JSX gets rendered.

您将看到createPortal ReactDOM.render两个参数:一些呈现的JSX,和类似于ReactDOM.render的目标元素,在该元素下呈现JSX。

If you render the Component and navigate to it, you should find it shows up quite well. You now need to add the appropriate onClick() handler to handle click events inside the inner modal UI as well as to navigate away from the modal if the user clicks outside the inner modal UI.

如果渲染组件并导航到它,应该会发现它显示得很好。 现在,您需要添加适当的onClick()处理函数,以处理内部模式UI内的单击事件,并且如果用户在内部模式UI之外单击,则从该模式导航。

You’d want to do this by listening for clicks in the right area and then stopping propagation so that the right behaviors arise depending on the region where the user clicks.

您希望通过在正确的区域中监听点击,然后停止传播来做到这一点,以便根据用户单击的区域出现正确的行为。

可重用性 (Reusability)

The above example is extremely basic, and is not intended to be a ready to use code snippet. Rather, this is a solution to tackling modals. You should absolutely customise the component according to your needs. Use the React principles of reusability to ensure that you’re not hard coding data in the Modal, and pass down the content and even smaller widgets as needed.

上面的示例非常基础,并且不打算立即使用。 而是,这是解决模式的解决方案。 您应该绝对根据需要自定义组件。 使用React的可重用性原理来确保您不会在Modal中对数据进行硬编码,并根据需要传递内容甚至是较小的小部件。

For example, in one of my projects, I present a modal when the user is going to delete something from the database. So my component is, say, called <DeleteThis />. It renders <Modal />, which is the overlay that dims the underlying <DeleteThis /> screen.

例如,在我的一个项目中,当用户要从数据库中删除某些内容时,我会显示一个模式。 因此,我的组件称为<DeleteThis /> 。 它呈现<Modal /> ,这是使基础<DeleteThis />屏幕变暗的叠加层。

render() {    return (      
); } renderActionButtons = () => { //return JSX that renders action buttons... return (
Delete
Cancel
); };

Within <Modal /> is an inner component called <InnerModal /> and this has the actual interactive component, with headers, content and text.

<Modal />内包含一个内部组件alled <Inne rModal />,它具有实际的交互式组件,包括标题,内容和文本。

So my <DeleteThis /> component creates props to pass down into <;Modal /> which in turn gets drilled down into <;InnerModal />, and so the render method in <DeleteThis /> looks like:

因此,我的<DeleteThis />组件创建了要向下传递into < ; Modal />的道具,而后者又将钻取d down into < ; InnerModal />,因此<DeleteThis />中的render method如下:

…with the actual Modal Component looking like:

…实际的模态组件如下所示:

import React from "react";import ReactDOM from "react-dom";import ModalInner from './modal-inner'function Modal(props) {  return ReactDOM    .createPortal(       
, document.querySelector("#modal") //target DOM element );}export default Modal;

and now, you’re finally able to render:

现在,您终于可以渲染:

Voilà, there you have it! Modals, with React Portal! Hope you enjoyed this ?

Voilà,就在那里! 使用React Portal的模式! 希望你喜欢这个吗?

And hope it saved you some ? ? ?…

希望它能为您节省一些时间? ? ?

If you would like to talk about your journey, I would love to listen. Tweet me . If you think what you just read could be useful to someone, please share it.

如果您想谈一谈您的旅程,我很想听听。 给我发 。 如果您认为您刚刚阅读的内容可能对某人有用,请与他人分享。

[Update] Quincy at FreeCodeCamp has relaunched the , and uses his incredible experience as an educator to pull together content that will help you on your journey. I was recently on and if you’re new to development, you should check it out to see how many people are like us, and how much is possible for us! You can also access the podcast on , , and or directly from .

[ 更新 ] FreeCodeCamp的Quincy重新推出了 ,并利用他作为教育工作者的令人难以置信的经验整理了有助于您旅途的内容。 我最近刚看过 ,如果您不熟悉开发,就应该查看一下,看看有多少人像我们一样,对我们有多少潜力! 您也可以在 , 和上访问播客,或直接从此 。

Follow my , my and, if you’re so inclined, hit me up on .

跟随我的和我的 ,如果您愿意,可以在上打我。

Founder at

创始人

翻译自:

react 模态对话框

转载地址:http://lfwzd.baihongyu.com/

你可能感兴趣的文章
react中<link>和<navlink>区别
查看>>
C# 生成随机数
查看>>
Psutil模块的应用
查看>>
session概述
查看>>
MATLAB 单变量函数一阶及N阶求导
查看>>
如何在网页端启动WinForm 程序
查看>>
[转载] Java并发编程:Lock
查看>>
MySQL之索引
查看>>
JAVA设计模式之单例模式
查看>>
优秀博客
查看>>
词法分析程序
查看>>
Java反射
查看>>
[ACM_模拟][ACM_数学] LA 2995 Image Is Everything [由6个视图计算立方体最大体积]
查看>>
1040 有几个PAT
查看>>
BZOJ 1412 [ZJOI2009]狼和羊的故事 | 网络流
查看>>
原型模式
查看>>
Hadoop RPC源码阅读-交互协议
查看>>
WASAPI、DirectSound/DS、WaveOut、Kernel Streaming/KS
查看>>
Perl按行分割文件
查看>>
根据现有表操作基于active record的model
查看>>