相思资源网 Design By www.200059.com

打算用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);
 }
`

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

标签:
React,对话框,React,模态框

相思资源网 Design By www.200059.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
相思资源网 Design By www.200059.com

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

暂无使用React手写一个对话框或模态框的方法示例的评论...

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。