我正在使用一些 ReactJS 組件構(gòu)建 Tabler 儀表板。起初我使用普通的 HTML 頁面和 Jinja2 模板,但我開始為一些組件實(shí)現(xiàn) ReactJS。
我不想使用太多第三方工具,例如react-tabler或bootstrap-tabler,因?yàn)樗鼊?chuàng)建了很多我可能并不真正需要的額外包。我已經(jīng)能夠使用 ReactJS 組件創(chuàng)建一個(gè)漂亮的 Tabler 儀表板,而無需這些包。
我現(xiàn)在遇到的唯一問題是顯示模態(tài)......現(xiàn)在這可以工作,但 CSS 轉(zhuǎn)換卻不起作用。至少一開始不是。我讓他們這樣工作:
// handle button click const handleEditClick = (row) => { setIsModalOpen(true); modalRef.current.style.display = "block"; // delay to make sure block is set first setTimeout(() => { modalRef.current.classList.add("show"); }, 100); };
問題是,我不太喜歡這個(gè)。感覺有點(diǎn)老套。
顯示模態(tài)效果很好,只需首先添加 style="display:block
屬性,然后添加 show
類。這樣我就可以在沒有太多額外 JavaScript 或其他內(nèi)容的情況下工作。但是 display:block
必須設(shè)置首先,如果沒有,它們似乎是同時(shí)設(shè)置的,或者可能是 display:block
稍后設(shè)置,所以你不會(huì)看到轉(zhuǎn)換。
我嘗試添加以下事件列表器 modalRef.current.addEventListener("transitionend", handleTransitionEnd);
,但我想這只適用于實(shí)際轉(zhuǎn)換,而不適用于更改樣式。
有沒有比 100 毫秒超時(shí)更簡(jiǎn)潔的方法?顯然,默認(rèn)情況下我無法添加 display:block
,因?yàn)檫@樣我的應(yīng)用程序由于位于我的應(yīng)用程序之上的透明模式而無法訪問。
這就是我現(xiàn)在修復(fù)它的方法。我使用了兩次 useEffect,這是為了防止類“show”與 display:block
樣式同時(shí)添加。
要關(guān)閉模態(tài)框,我實(shí)際上可以使用 transitionend
事件偵聽器。
const MyComponent = () => { const [isModalOpen, setIsModalOpen] = useState(false); const [isButtonClicked, setIsButtonClicked] = useState(false); const modalRef = useRef(null); const [isStyleApplied, setIsStyleApplied] = useState(false); const [isClassApplied, setIsClassApplied] = useState(false); const handleEditClick = () => { setIsModalOpen(true); setIsButtonClicked(true); }; useEffect(() => { const applyStyle = () => { if (modalRef.current && !isStyleApplied && isButtonClicked) { modalRef.current.style.display = 'block'; setIsStyleApplied(true); } }; applyStyle(); }, [isButtonClicked, isStyleApplied]); useEffect(() => { const applyClass = () => { if (modalRef.current && isButtonClicked && isStyleApplied && !isClassApplied) { modalRef.current.classList.add('show'); setIsClassApplied(true); } }; applyClass(); }, [isButtonClicked, isStyleApplied, isClassApplied]); const handleCloseModal = () => { setIsModalOpen(false); modalRef.current.addEventListener("transitionend", handleTransitionEnd); modalRef.current.classList.remove("show"); function handleTransitionEnd() { modalRef.current.removeEventListener("transitionend", handleTransitionEnd); modalRef.current.style.display = "none"; } setIsButtonClicked(false); setIsStyleApplied(false); setIsClassApplied(false); }; return ( handleEditClick(row)} href="#">Open Modal); }