javascript - 在 React 中侦听 JavaScript 媒体查询
问题描述
我正在尝试实现在 React 中找到的媒体查询概念。如下所示,我得到以下信息:
TypeError: isMobile.addListener is not a function
function App() {
// Saving current page to state
let location = useLocation();
useEffect(() => {
useStore.setState({ currentPage: location })
}, [location]);
// Check if viewing in landscape on mobile
const isMobile = window.matchMedia("only screen and (max-width: 830px)").matches;
const setOrientation = (e) => {
if (e.isMobile) {
if (window.innerHeight > window.innerWidth){
// is not landscape
} else{
// is landscape
}
}
}
useEffect(() => {
setOrientation(isMobile)
isMobile.addListener(setOrientation)
return () => isMobile.removeEventListener(setOrientation)
}, []);
return (
<div className="App"></div>
);
}
export default App;
我究竟做错了什么?
解决方案
因此MediaQueryList matches
方法返回一个布尔值。
您应该只返回您的MediaQueryList以便以后能够向其添加监听器:
const isMobile = window.matchMedia("only screen and (max-width: 830px)")
推荐阅读
- git - 是否可以使用 Libgit2sharp 从特定标签克隆?
- macos - 为什么自制 apache 在启动时不启动?
- c# - 错误:IsObjectMonoBehaviour 只能从主线程调用
- caching - 什么是 CMake 缓存?
- c# - Unity 测试运行程序中未调用设置/拆卸,测试被阻止
- vuejs2 - 在 v-for 循环中使用插槽或插槽范围来访问属性?
- pandas - 将 Pandas 子图组合成一个图形
- css - 如何将标题定位在某个位置?
- netbeans - 为 tinylog 创建 Netbeans 代码模板
- python - 创建一个包含超过 3 个元音的所有单词(包括连字符的单词)的列表