使用React手写一个对话框或模态框

《使用React手写一个对话框或模态框》

打算用React写对话框已经很长一段时间,现在是时候兑现承诺了。实际上,写起来相当简单。

核心在于使用React的接口React.createPortal(element, domContainer)。该接口将element渲染后的DOM节点嵌入domContainer(通常是document.body),并保证只嵌入一次。

欢迎订阅
我的博客

所以,我们可以这样写一个对话框或模态框:

function Dialog() {
    return React.createPortal( <div>Dialog contents</div>, document.body )
}

一个新的div会出现在body内部:
《使用React手写一个对话框或模态框》

一个完整DEMO:

《使用React手写一个对话框或模态框》
点击运行DEMO


class Modal extends React.Component {
  render() {
    const {
      visible,
      onClose
    } = this.props
    return visible && ReactDOM.createPortal(<StyledModalRoot>
      <div className="box">
        Content
        <br/>
        <button onClick={onClose}>Close</button>
      </div>
    </StyledModalRoot>, document.body)
  }
}

class App extends React.Component {
  state = {
    visibleModal: false
  }
  showModal = () => this.setState( { visibleModal: true } )
  handleCloseModal = () => this.setState( { visibleModal: false } )
  render() {
    const { visibleModal } = this.state
    return <div style={{padding: '20px'}}>
    <button onClick={ this.showModal }>Show Modal</button>
    <Modal visible={visibleModal} onClose={ this.handleCloseModal } />
  </div>
  }
}

const StyledModalRoot = styled.div`
  position: fixed;
  z-index: 1001;
  left: 0;
  top: 0;
  display: grid;
  place-items: center;
  width: 100%;
  height: 100%;
  background: rgba( 0, 0, 0, 0.2 );

  >.box {
    position: relative;
    display: grid;
    place-items: center;
    width: 80%;
    height: 80%;
    background: white;
    border-radius: 10px;
    box-shadow: 0px 3px 5px -1px rgba(0,0,0,0.2), 0px 5px 8px 0px rgba(0,0,0,0.14), 0px 1px 14px 0px rgba(0,0,0,0.12);
  }
`

感谢你花时间阅读这篇文章。如果你喜欢这篇文章,欢迎点赞、收藏和分享,让更多的人看到这篇文章,这也是对我最大的鼓励和支持!
欢迎在Star和订阅我的原创前端技术博客

    原文作者:前端
    原文地址: https://segmentfault.com/a/1190000018967814
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞