我正在嘗試使用 Next.js 中的 DOM 媒體查詢來更改我的應用程式的結構。普通媒體查詢 (CSS) 沒有問題。在“純”React 中,我可以這樣做:
function HomePage () {
const [landscape, setLandscape] = useState(false)
useEffect(() => {
const landscapeHandler = e => {
console.log ("Change in landscape")
setLandscape({matches: e.matches});
}
window.matchMedia("((orientation:landscape)").addEventListener('change', landscapeHandler);
return () => {
window.removeEventListener('change', landscapeHandler);
}
}, [])
}
但是,在使用 Next 時,更改螢屏的方向根本沒有任何作用。有解決方法嗎?我一直認為 useEffect 只是客戶端,因此是進行此類媒體查詢的正確位置......在此先感謝!
uj5u.com熱心網友回復:
Next.js 首先在服務器中執行代碼,然后在客戶端中執行代碼。因此,當它在服務器中執行時,視窗將是未定義的。
你可以像下面的代碼那樣做,
useEffect(() => {
if (typeof window !== "undefined") {
window.matchMedia("((orientation:landscape)").addEventListener('change', landscapeHandler);
}
// component Will Unmount
return () => {
if (typeof window !== "undefined") {
window.removeEventListener('change', landscapeHandler);
}
};
}, []);
uj5u.com熱心網友回復:
您本可以使用“orientationchanged”偵聽器,但我認為它已經貶值了。
您可以嘗試使用“調整大小”偵聽器。
useEffect(() => {
const handleChange = () => {
const width = document.documentElement.clientWidth
const height = document.documentElement.clientHeight
const orientation = width > height ? 'landscape' : 'portrait';
console.log('orientation: ', orientation, 'width', width, 'height', height)
}
if (typeof window !== 'undefined') {
const unsub = window.addEventListener('resize', handleChange)
return () => unsub();
}
},[])
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/432113.html
標籤:javascript 反应 下一个.js 客户端
