内容简介:打算用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 内部:
一个完整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);
}
`
是不是很简单?
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- 如何使用JavaScript构建模态框插件
- 自定义带动画效果的模态框
- Angluar-模态视图构建简析(A)
- React 30 秒速学:制作模态框组件
- BERT在多模态领域中的应用
- 通用的图像-文本语言表征学习:多模态预训练模型 UNITER
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Web Scalability for Startup Engineers
Artur Ejsmont / McGraw / 2015-6-23 / USD 34.81
Design and build scalable web applications quickly This is an invaluable roadmap for meeting the rapid demand to deliver scalable applications in a startup environment. With a focus on core concept......一起来看看 《Web Scalability for Startup Engineers》 这本书的介绍吧!