Do you really know react portals

Song in the clouds 2020-11-09 11:30:26
really know react portals


In the past, when writing global masks , I usually use fixed location , The sample code is as follows :

.modal {
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
z-index:500;
background: black;
}

This is to implement the global mask layer ,modal The content is controlled by itself . But there's a problem with that , As follows :

You can see that the contents of this pop-up window are not in body The next floor , It's nested in layers dom inside , There are two disadvantages :

  1. DOM The structure is not elegant enough
  2. The style of the parent component may affect the style of the child component

Here's a real case , Colleagues also use it fixed The global pop-up window is generated by positioning , But found that the button click can not change the pop-up window display , Then I found that I wrote a wonderful code , The code looks like this :

<!-- Here are the subcomponents -->
return (
<button>
<span>toggle visible</span>
<modal visible={visible}></modal>
</button>
)

Then I found that the button can't be controlled modal Show hidden , Because of this button Seriously affected modal act .
This kind of problem is very difficult to solve , You don't know what wonderful code the user wrote , At this time, consider other ways to avoid this problem . In user use modal When , This modal Of dom It is actually mounted under the current component , Imagine if you put this DOM Directly inserted into the body Is it possible to avoid these problems
fortunately React Provides the ability to , So let's talk about that react Provided in the child node rendering outside of the parent component DOM Node Portal

Portal Introduce

Portal Be able to render child components to other than the parent component DOM Trees , It is usually used in scenarios where a child component needs to be detached from the parent component's container , There are the following scenarios :

  • Dialog Dialog box
  • Tooltip Text prompt
  • Popover pop-up
  • Loader overall situation loader

Here's how he uses it :

React.createPortal();

The first parameter (child) Is anything that can be rendered React Subelement , For example, an element , String or fragment. The second parameter (container) It's a DOM Elements .
Here's how to use react.createPortal A simple example of :

const Modal = ({message, visible, onClose, children}) => {
if (!visible) return null;
return ReactDOM.createPortal(
<div class="modal">
<span className="message">{message}</span>
<button onClick={onClose}>Close</button>
</div>
, domNode)
}

although portal Break away from the container restrictions of the parent component , But his performance and normal React Components are consistent . Can also receive props and context. This is because portal There is still react In the hierarchical tree of .

Why Portal

Just like a case mentioned at the beginning of the article , In a component, we need to use modal Popup , Most of the time we can use fixed Positioning allows the pop-up window to be displayed globally , But in special cases , This modal The pop-up window may display abnormal . So at this time, if we use portal In a direct way modal Of dom The structure is separated from the container of the parent component , You can avoid this problem .

const Modal = ({message, isOpen, onClose, children}) => {
if (!isOpen) return null;
return ReactDOM.createPortal(
<div className="modal">
<span>{message}</span>
<button onClick={onClose}>Close</button>
</div>
, document.body)
}
function Component() {
const [open, setOpen] = useState(false)
return (
<div className="component">
<button onClick={() => setOpen(true)}></button>
<Modal
message="Hello World!"
isOpen={open}
onClose={() => setOpen(false)}
/>
</div>
)
}

The above code guarantees that , No matter how deep the subcomponents are nested , This modal Can and root Same level . Use chrome Check dom structure , You can see the following structure

Use Portal Points for attention

In the use of Portal When , You need to know that even though Portal Can be placed in DOM Anywhere in the tree , But behavior and ordinary React Component behavior is consistent . because portal Still exists in React Trees , And with the DOM Trees It's not about the position in , So whether its child node is portal, image context Such features are unchangeable .
Here's a summary of some considerations .

  1. Event Bubbling : A from portal Internally triggered events will bubble until they contain React The ancestors of trees , Even if these elements are not DOM Trees The ancestors of .
  2. Life cycle : Even through Portal Created elements , This element still has its life cycle, such as componentDidMount wait
  3. scope : Portal Will only affect HTML The structure of will not affect React Tree structure
  4. Mount node : When using Portal You have to define a real DOM Node as Portal The mount entry of the component

summary

When we need to be in normal DOM When rendering sub components outside the structure ,React Portal Very useful , You don't have to pass it React The component tree hierarchy destroys the default behavior of event propagation , This is rendering, like pop-up window 、 Tips are very useful

Welcome to your attention 「 Learn from the front end 」, Front end learning does not get lost or add wechat ssdwbobo, Exchange and study together
版权声明
本文为[Song in the clouds]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple