使用React手写一个对话框或模态框的方法示例

2022-10-20,,,,

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

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

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

function dialog() {
  return react.createportal( <div>dialog contents</div>, document.body )
}

一个新的div会出现在body内部:

一个完整demo:

点击运行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);
 }
`

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

《使用React手写一个对话框或模态框的方法示例.doc》

下载本文的Word格式文档,以方便收藏与打印。