Zei*_*aki 19 javascript reactjs
我已经使用 React 创建了一个基本模态,没有任何库,它工作得很好,现在当我单击模态之外时,我想关闭模态。
这是CodeSandbox实时预览
我的index.js:
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
constructor() {
super();
this.state = {
showModal: false
};
}
handleClick = () => {
this.setState(prevState => ({
showModal: !prevState.showModal
}));
};
render() {
return (
<>
<button onClick={this.handleClick}>Open Modal</button>
{this.state.showModal && (
<div className="modal">
I'm a modal!
<button onClick={() => this.handleClick()}>close modal</button>
</div>
)}
</>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
Run Code Online (Sandbox Code Playgroud)
小智 39
实现此目的的最简单方法是在包装器中调用 closeModal 函数并停止在实际模态中的传播
例如
<ModalWrapper onClick={closeModal} >
<InnerModal onClick={e => e.stopPropagation()} />
</ModalWrapper>
Run Code Online (Sandbox Code Playgroud)
Sec*_*per 10
如果不使用ref,会有点棘手
观看此CodeSandBox
或者
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
constructor() {
super();
this.state = {
showModal: false
};
}
handleClick = () => {
if (!this.state.showModal) {
document.addEventListener("click", this.handleOutsideClick, false);
} else {
document.removeEventListener("click", this.handleOutsideClick, false);
}
this.setState(prevState => ({
showModal: !prevState.showModal
}));
};
handleOutsideClick = e => {
if (!this.node.contains(e.target)) this.handleClick();
};
render() {
return (
<div
ref={node => {
this.node = node;
}}
>
<button onClick={this.handleClick}>Open Modal</button>
{this.state.showModal && (
<div className="modal">
I'm a modal!
<button onClick={() => this.handleClick()}>close modal</button>
</div>
)}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以通过为与模态主体相邻的模态背景创建一个 div 来实现这一点。使用绝对位置和 100% 高度和宽度值使其覆盖整个屏幕。
这样,模态主体就位于背景之上。如果您单击模态主体,则不会发生任何事情,因为背景没有接收到单击事件。但如果您单击背景,则可以处理单击事件并关闭模式。
关键是模态背景不会包裹模态主体,而是位于其旁边。如果它包裹了主体,那么对背景或主体的任何点击都会关闭模式。
const {useState} = React;
const Modal = () => {
const [showModal,setShowModal] = useState(false)
return (
<React.Fragment>
<button onClick={ () => setShowModal(true) }>Open Modal</button>
{ showModal && (
<React.Fragment>
<div className='modal-backdrop' onClick={() => setShowModal(false)}></div>
<div className="modal">
<div>I'm a modal!</div>
<button onClick={() => setShowModal(false)}>close modal</button>
</div>
</React.Fragment>
)}
</React.Fragment>
);
}
ReactDOM.render(
<Modal />,
document.getElementById("react")
);Run Code Online (Sandbox Code Playgroud)
.modal-backdrop {
position: absolute;
top: 0;
left: 0;
background: #252424cc;
height: 100%;
width: 100vw;
}
.modal {
position: relative;
width: 70%;
background-color: white;
border-radius: 10px;
padding: 20px;
margin:20px auto;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>Run Code Online (Sandbox Code Playgroud)
我用功能组件来解释一下:
modal首先创建 ref 来获取对该元素的引用
import { useEffect, useState, useRef } from "react";
const [isModalOpen,setIsModalOpen]=useState(false)
const modalEl = useRef();
<div className="modal" ref={modalEl} >
I'm a modal!
<button onClick={() => this.handleClick()}>close modal</button>
</div>
Run Code Online (Sandbox Code Playgroud)
第二步useEffect创建一个事件处理程序来检测模态元素外部的事件。为此,我们需要capture phase在一个元素上实现。(这里解释一下:什么是事件冒泡和捕获?)。基本上,我们将注册一个事件处理程序,以便当浏览器检测到任何事件时,浏览器将开始从顶部父 HTML 元素查找事件处理程序,如果找到它,它将调用它。
useEffect(() => {
const handler = (event) => {
if (!modalEl.current) {
return;
}
// if click was not inside of the element. "!" means not
// in other words, if click is outside the modal element
if (!modalEl.current.contains(event.target)) {
setIsModalOpen(false);
}
};
// the key is using the `true` option
// `true` will enable the `capture` phase of event handling by browser
document.addEventListener("click", handler, true);
return () => {
document.removeEventListener("click", handler);
};
}, []);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
76832 次 |
| 最近记录: |