您好,登錄后才能下訂單哦!
打算用React寫對話框已經(jīng)很長一段時間,現(xiàn)在是時候兌現(xiàn)承諾了。實際上,寫起來相當(dāng)簡單。
核心在于使用React的接口React.createPortal(element, domContainer)
。該接口將element
渲染后的DOM節(jié)點嵌入domContainer
(通常是document.body
),并保證只嵌入一次。
所以,我們可以這樣寫一個對話框或模態(tài)框:
function Dialog() { return React.createPortal( <div>Dialog contents</div>, document.body ) }
一個新的div
會出現(xiàn)在body
內(nèi)部:
一個完整DEMO:
點擊運(yùn)行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); } `
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。