ReactJS:如何确定是在移动浏览器还是桌面浏览器上查看应用程序 [英] ReactJS: How to determine if the application is being viewed on mobile or desktop browser

查看:54
本文介绍了ReactJS:如何确定是在移动浏览器还是桌面浏览器上查看应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ReactJS中,有没有一种方法可以确定该网站是在移动设备上还是在桌面设备上查看?因为,我想根据哪种设备来渲染不同的东西.

In ReactJS, is there a way to determine if the website is being viewed on mobile or desktop? Because, depending on which device I would like to render different things.

谢谢

推荐答案

使用React钩子的简单解决方案

Simple solution using react hooks

const [width, setWidth] = useState<number>(window.innerWidth);
function handleWindowSizeChange() {
        setWidth(window.innerWidth);
    }
useEffect(() => {
        window.addEventListener('resize', handleWindowSizeChange);
        return () => {
            window.removeEventListener('resize', handleWindowSizeChange);
        }
    }, []);

let isMobile: boolean = (width <= 768);

这篇关于ReactJS:如何确定是在移动浏览器还是桌面浏览器上查看应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆