打算用React写对话框已经很长一段时间,现在是时候兑现承诺了。实际上,写起来相当简单。
10年积累的成都做网站、网站设计经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站设计后付款的网站建设流程,更有下冶免费网站建设让你可以放心的选择与我们合作。
核心在于使用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手写一个对话框或模态框的方法示例
浏览地址:https://www.cdcxhl.com/article38/gepjsp.html
成都网站建设公司_创新互联,为您提供自适应网站、商城网站、网站排名、域名注册、响应式网站、营销型网站建设
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联