簡體   English   中英

防止 HTML 模態對話框關閉

[英]Prevent HTML Modal Dialog from Closing

我想使用<dialog> HTML 元素來創建模態。 我試圖限制用戶在某些情況下關閉模式的能力,並嘗試在觸發對話框的onClose() e.preventDefault() ,但是,這並不能阻止對話框關閉。

控制模態dialog是否可以關閉的預期方法是什么?

 ReactDOM.render( <App />, document.getElementById("root") ); function App() { const modalRef = React.createRef() function handleClose(e) { // press escape button to trigger this e.preventDefault() console.log('closing') } return( <React.Fragment> <button onClick={() => modalRef.current.showModal()}> Open modal </button> <dialog ref={modalRef} onClose={handleClose}> Hello world </dialog> </React.Fragment> ) }
 <div id='root'></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

您的代碼中沒有錯誤,但在對話框元素中您需要監聽onCancel事件而不是onClose事件。

 ReactDOM.render( <App />, document.getElementById("root") ); function App() { const modalRef = React.createRef() function handleClose(e) { // press escape button to trigger this e.preventDefault() console.log('closing') } return( <React.Fragment> <button onClick={() => modalRef.current.showModal()}> Open modal </button> <dialog ref={modalRef} onCancel={handleClose}> Hello world </dialog> </React.Fragment> ) }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM