码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-09-28 21:14:15      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:embed   import   style   created   nal   wrap   under   tool   func   

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

标签:embed   import   style   created   nal   wrap   under   tool   func   

原文地址:http://www.cnblogs.com/Answer1215/p/7608520.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!