[英]Prevent HTML Modal Dialog from Closing
I want to use the <dialog>
HTML element to create a modal.我想使用
<dialog>
HTML 元素来创建模态。 I'm trying to restrict the user's ability to close the modal under some circumstances, and tried to call e.preventDefault()
when the dialog's onClose()
is fired, however, that doesn't stop the dialog from closing.我试图限制用户在某些情况下关闭模式的能力,并尝试在触发对话框的
onClose()
e.preventDefault()
,但是,这并不能阻止对话框关闭。
What is the intended way to control whether modal dialog
can be closed or not?控制模态
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>
There is no error in your code but in the dialog element you need to listen to onCancel
event instead of onClose
event.您的代码中没有错误,但在对话框元素中您需要监听
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.