App.jsx
import React, { useState } from "react";
import Modal from "./components/Modal/Modal";
export default function App() {
const [showModal, setShowModal] = useState(false);
return (
<div className="app">
<p className="ppp">Sample text</p>
<div className="modal_menu_wrap">
<div className="modal_menu">
<button
onClick={() => {
setShowModal(true);
}}
className="open-btn"
>
Open/Close
</button>
<Modal active={showModal} setShowModal={setShowModal} />
</div>
</div>
</div>
);
}
字符串
index.css
.open-btn {
padding: 10px 15px;
border: none;
background-color: black;
color: aliceblue;
cursor: pointer;
}
.open-btn:hover {
scale: 1.05;
}
.modal_menu_wrap {
display: flex;
justify-content: center;
border: 1px solid rgb(255, 0, 0) !important;
}
.modal_menu {
width: 100%;
max-width: 200px;
border: 1px solid rgb(255, 0, 0) !important;
}
型
Modal.jsx
import styles from "./modal.module.css";
import React, { useEffect, useState } from "react";
export default function Modal({ active, setShowModal }) {
const [showContent, setShowContent] = useState(false);
const closeModal = () => {
setShowContent(false);
setTimeout(() => {
setShowModal(false);
}, 500);
};
useEffect(() => {
if (active) {
setShowContent(true);
}
}, [active]);
if (!active) return null;
return (
<div
className={
showContent ? `${styles.modal} ${styles.showModal}` : `${styles.modal}`
}
>
<p className="ppp"></p>
<div onClick={closeModal} className={styles.closeBtn}>
<span>×</span>
</div>
</div>
);
}
型
modal.module.css
.modal {
position: absolute;
width: 100%;
max-width: 200px;
height: 300px;
background-color: azure;
border-radius: 10px;
z-index: 2;
opacity: 0.5;
border: 1px solid rgb(255, 0, 0) !important;
transform: translateY(-100vh);
transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
.showModal {
opacity: 1;
transform: translateY(0);
z-index: 2;
}
.closeBtn {
position: absolute;
top: 10px;
right: 20px;
cursor: pointer;
z-index: 9;
border: 1px solid rgb(255, 0, 0) !important;
}
.closeBtn span {
display: block;
font-size: 2rem;
font-weight: bold;
transition: transform 0.2s ease;
}
.closeBtn span:hover {
transform: scale(1.2);
}
型
当您单击“打开/关闭”按钮以及在元素字段外单击时,元素必须出现和消失。我为按钮指定了一个值onClick={() => {setShowModal( !showModal);}}
,但在本例中,动画消失了。元素必须从dom中完全消失。不应有带十字的按钮。演示-https://codesandbox.io/s/serverless-dust-8vj86d?file=/src/index.css
2条答案
按热度按时间lbsnaicq1#
简单编辑2个文件
第一个
使打开/关闭按钮通过将新值设置为旧值的倒数来切换状态!showModal在
App.js
文件中
然后
我删除了
if (!active) return null;
这一行,这是一个糟糕的使用react的方法!无意冒犯,但这可能会影响应用程序的性能。并在此之后添加了一个检查,如果它是活动的,则会删除该类
active && showContent
,这意味着如果active为== true,则执行文件Modal.jsx
中运算符右侧的代码型
最后的代码是:
App.jsx
型
Modal.jsx
型
ipakzgxi2#
更好的方法是将动画添加到类中。
然后将组件的样式设置为动画最后一帧中的状态。同样简单的是,当您将className添加到组件时,动画发生并通过在动画结束时删除className返回到最后一个状态。所以你可以编辑
字符串