我有一个为桌面视图优化的应用程序。如果用户在移动视图中打开它,是否有任何方法可以使应用程序警告用户,并要求他们在桌面视图中打开它?
检测用户是否正在移动设备上浏览您的网站的一个简单方法是检查屏幕的大小。您可以使用JavaScript完成此操作:
const isMobile = window.matchMedia("only screen and (max-width: 760px)").matches;
if(isMobile){
// Display message onto screen or do whatever you want
}
下面是React功能组件中的一个简单实现:
function displayOnlyOnDesktop() {
const isMobile = window.matchMedia("only screen and (max-width: 760px)").matches;
if(isMobile){
return <div>Sorry, this website is only available on desktop devices.</div>
}
return <div>Hooray, you're on a desktop device, so you can see this website!</div>
}
在根组件中,
const [showMobileWarning, setShowMobileWarning] = useState(false)
useEffect(() => {
if(window.innerWidth <= 800)
setShowMobileWarning(true)
}, [])
然后使用showmobilewarning
有条件地显示警告消息。
return(
.........
{showMobileWarning ? <SomeWarning />}
.........
)