[React] Render Elements Outside the Current React Tree using Portals in React 16

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[React] Render Elements Outside the Current React Tree using Portals in React 16相关的知识,希望对你有一定的参考价值。

By default the React Component Tree directly maps to the DOM Tree. In some cases when you have UI elements like overlays or loading bars this can be limiting. React 16 therefor ships with the new portal feature allowing you to attach parts of the Component tree inside a different root element.

This lesson explores the new functionality by building an <Overlay/> component that renders out its children and creates a closeable overlay outside its DOM node.

 

It is important to understand what portals is good for. 

Let\'s see what if we don\'t have portals:

 

 

As we can see, the overlay component is nested inside our wrapper component:

 

Now let\'s see what if we use portals:

 

This time we have created a empty \'overlay-root\' div inside the html body.

  <body>
    <div id="root"></div>
    <div id="overlay-root">
      
    </div>
  </body>

And inside our Overlay compmonet, we render the component into this \'overlay-root\' div:

 If now we open devtool to see DOM structure:

As we can see Overlay-root is spreated from wrapper component, and it is reuseable and provide a much clean DOM structure.

 

以上是关于[React] Render Elements Outside the Current React Tree using Portals in React 16的主要内容,如果未能解决你的问题,请参考以下文章

当有条件地渲染两个组件时,每个组件都包含一个 react-native-elements <Input>,激活一个会导致组件异常/不渲染

你可以在实例化后向 React JSX 元素添加一个键吗?

[Vue] Conditionally Render DOM Elements in Vue.js (v-if v-else v-show)

React Native 速成 002 — 使用 UI框架 React Native Elements

如何使用 react-stripe-elements 输入组件设置边框样式?

ReactNative学习之控件:react-native-elements