我很难理解这个非常简单的代码中的问题:
export default function CustomPopup({wi,he,children}) {
//some code
const [popupSize,setPopupSize] = useState([`${wi}px`,`${he}px`])
const handlePopupSize = () =>{
let c = [];
(window.innerWidth < (wi/0.9)) ? c[0] = `90%` : c[0] = `${wi}px`;
(window.innerHeight < (he/0.8)) ? c[1] = `80%` : c[1] = `${he}px`;
if (c != popupSize) { setPopupSize(c) };
}
window.addEventListener("resize", handlePopupSize)
return (
<div className="popup--page--wrapper">
<div className="popup--box" style={{width: popupSize[0], height: popupSize[1]}}>
{ children }
</div>
</div>
)
}当我调整页面大小时,页面会严重滞后,甚至会导致浏览器出现bug。代码似乎有问题,但我找不到。提前感谢!
发布于 2020-11-29 20:50:21
您需要将add event listener放入useEffect。
import React, { useState, useEffect } from 'react'
.....
.....
useEffect(() => {
window.addEventListener("resize", handlePopupSize)
return () => window.removeEventListener("resize", handlePopupSize)
},[])您当前的代码创建了一个addEventListeners循环,因为在每次渲染时都会创建一个侦听器,而设置状态会导致每次调整大小时都会重新渲染。
https://stackoverflow.com/questions/65060227
复制相似问题