P粉2877263082023-08-31 10:43:01
I feel stupid after spending so much time solving this problem, but I wanted to post the answer in case anyone else has a similar problem.
The problem is related to React's rendering process. <Modal/>
is re-rendered every time the media query is updated, which happens when the orientation changes on mobile devices. So when the modal re-renders on orientation change, the video closes. I'm not sure why the media query is causing a re-render (maybe something to do with the settings of ChakraUI hooks), if anyone has this problem maybe it can be elaborated on. However, switching to status solved the problem.
The solution is simple:
const [wIsSmallerThan48em] = useMediaQuery("(max-width: 48em)"); const [hIsSmallerThan30em] = useMediaQuery("(max-height: 30em)"); const [showModal, setShowModal] = useState(false); useEffect(() => { if (wIsSmallerThan48em || hIsSmallerThan30em){ setShowModal(true) } else { setShowModal(false) } }, [wIsSmallerThan48em, hIsSmallerThan30em]) // 在移动设备上无论是纵向还是横向都渲染“错误”模态框 if (showModal){ return ( <Modal> <Video src={MyVideo} /> </Modal> ) } else { return ( <Visualizer /> ) }