[进阶指南] Portal( Day26 )

Portal 提供一个优秀方法来让 children 可以 render 到 parent component DOM 树以外的 DOM 节点。

  • 第一个参数(myComponent)是任何可 render 的 React child,例如 element、string 或者 fragment。
  • 第二个参数(elDOM)则是一个在 React 之外的 DOM element。
const elDOM = querySelector("#elementOutsideReact")
funciton () myComponent {

}
ReactDOM.createPortal(myComponent, elDOM)

一个 pop up 的实作:

Codepen 完整连结

透过 Portal 进行 Event Bubbling

在一般的例子可以将事件摆在 button 上,但有时候也会利用 Event buuble 扩大触及点。
在 html 档里面写的结构是 sibling 同一层的节点,但是可以抓的 bubble 的事件,因为 portal 之後节点还是在 React DOM tree 的结构里面。

<div id="app-root"></div>
<div id="modal-root"></div>

render code 改写:

return (
  <div className="App" onClick={this.togglePopup}> //挂在最外层
    <h1>Hello</h1>
    <TestLightBox>
      { this.state.showPopup ? <div className="lightBox">
        <div className="content">
          <h2>Start editing to see some magic happen!</h2>
          <button onClick={this.togglePopup}>关闭讯息</button>
        </div>
      </div> : ''}
    </TestLightBox>
    <button>显示更多讯息</button>
  </div>
);

以上今天。

参考资料:
https://zh-hant.reactjs.org/docs/portals.html


<<:  [Day28]-网路爬虫

>>:  Day 25 : 案例分享(7.4) 库存与制造 - 工单与工作中心

【心得】你今天种菜了吗? grid之路-grid的使用(2)

前言 昨天介绍了用grid-template-areas 来填格子 grid-template-ar...

成员 1 人:在骄傲时刻创业,在烦闷时刻立志

「我要开除老板。」所以,创业。 「我要换掉主管。」所以,创业。 「我要宰了客户。」所以,创业?......

把Nano板run起来

先说,我是用mac双系统的win10,本来想在mac os做,但是下载下来的说明书里有个自己的驱动程...

[Day 27] 实作 Redis PubSub Keyspace Notification 订阅 Session Key Expired 事件通知

session authentication 的机制是 登入时建立 sessionId 储存 ses...

Day9:今天来聊一下Parrot Security的Nmap

Nmap是一款用於网路发现和安全稽核网路安全工具,Nmap是Network Mapper的简称 Nm...