简体   繁体   English

ReactJS:如何确定应用程序是在移动浏览器还是桌面浏览器上查看

[英]ReactJS: How to determine if the application is being viewed on mobile or desktop browser

In ReactJS, is there a way to determine if the website is being viewed on mobile or desktop? ReactJS,有没有办法判断网站是在手机上浏览还是在桌面上浏览? Because, depending on which device I would like to render different things.因为,根据不同的设备,我想渲染不同的东西。

Thank you谢谢

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);
    }
}, []);

const isMobile = width <= 768;

You can use React Device Detect Package您可以使用React 设备检测包

This package uses the user-agent of the browser rather than the screen size.这个包使用浏览器的user-agent而不是屏幕大小。

This can be helpful when wanting to display different things if on desktop vs mobile or certain links based on the device如果想要在桌面与移动设备或基于设备的某些链接上显示不同的内容,这可能会很有帮助

Installation安装

To install, you can use npm or yarn:要安装,您可以使用 npm 或 yarn:

# For NPM:
npm install react-device-detect --save

# For Yarn
yarn add react-device-detect

Usage用法

Example:例子:

import {BrowserView, MobileView} from 'react-device-detect';

const MyComponent = () => {
    return (
        <>
            <BrowserView>
                <h1>This is rendered only in browser</h1>
            </BrowserView>
            <MobileView>
                <h1>This is rendered only on mobile</h1>
            </MobileView>
        </>
    );
};

if you don't need a view, you can use isMobile for conditional rendering如果不需要视图,可以使用isMobile进行条件渲染

import {isMobile} from 'react-device-detect';

const MyComponent = () => {
    if(isMobile) {
        return (
            <div> This content is available only on mobile</div>
        )
    }
    return (
        <div> content... </div>
    );
};

Taken from React Device Detect README with a little modification取自React Device Detect README ,稍作修改

I further enhanced Volobot's answer.我进一步增强了 Volobot 的答案。 I'd created a hook as below and it works like charm :)我创建了一个如下的钩子,它的作用就像魅力:)

import React, {useEffect, useState} from "react";

const useCheckMobileScreen = () => {
    const [width, setWidth] = useState(window.innerWidth);
    const handleWindowSizeChange = () => {
            setWidth(window.innerWidth);
    }

    useEffect(() => {
        window.addEventListener('resize', handleWindowSizeChange);
        return () => {
            window.removeEventListener('resize', handleWindowSizeChange);
        }
    }, []);

    return (width <= 768);
}

export default useCheckMobileScreen

What you are looking for is called react-responsive .您正在寻找的东西称为react-responsive You can find it here你可以在这里找到

Here is how to use quick guide from their repo:以下是how to use他们的仓库中的快速指南:

var MediaQuery = require('react-responsive');

var A = React.createClass({
  render: function(){
    return (
      <div>
        <div>Device Test!</div>

        <MediaQuery minDeviceWidth={1224}>
          <div>You are a desktop or laptop</div>
        </MediaQuery>
        <MediaQuery maxDeviceWidth={1224}>
          <div>You are a tablet or mobile phone</div>
        </MediaQuery>

        <MediaQuery orientation='portrait'>
          <div>You are portrait</div>
        </MediaQuery>
        <MediaQuery orientation='landscape'>
          <div>You are landscape</div>
        </MediaQuery>

        <MediaQuery minResolution='2dppx'>
          <div>You are retina</div>
        </MediaQuery>
      </div>
    );
  }
});

Why to complicate things when you can use one line of vanilla javascript code?当你可以使用一行 vanilla javascript 代码时,为什么要把事情复杂化?

Use window.screen object to get width of current screen.使用window.screen对象获取当前屏幕的宽度。 For example window.screen.width will return value of current width of client in pixels.例如window.screen.width将返回客户端当前宽度的值(以像素为单位)。

Use it inside if (window.screen.width >= 1280) { /* conditional statements */ }if (window.screen.width >= 1280) { /* conditional statements */ }使用它

I hope that it helps.我希望它有所帮助。 Thank you :-)谢谢 :-)

Create a Custom Hook and Listen to Resize, load, orientationchange and reload will rerender the component where you have used this hook.创建一个自定义 Hook 并监听 Resize、load、orientationchange 和 reload 将重新渲染您使用此钩子的组件。

  import { useState, useEffect } from 'react';

  const useDeviceDetect = () => {
    const checkForDevice = () => {
      let windowWidth = window.innerWidth;
      if (windowWidth < 767.98) {
        return true;
      } else {
        return false;
      }
    };

    const [isMobile, setIsMobile] = useState(checkForDevice());

    useEffect(() => {
      const handlePageResized = () => {
        setIsMobile(checkForDevice);
      };

      window.addEventListener('resize', handlePageResized);
      window.addEventListener('orientationchange', handlePageResized);
      window.addEventListener('load', handlePageResized);
      window.addEventListener('reload', handlePageResized);

      return () => {
        window.removeEventListener('resize', handlePageResized);
        window.removeEventListener('orientationchange', handlePageResized);
        window.removeEventListener('load', handlePageResized);
        window.removeEventListener('reload', handlePageResized);
      };
    }, []);

    return {
      isMobile,
    };
  };

  export default useDeviceDetect;

I used this method for React and it works great in 2020. Thanks @Anubahav Gupta我将这种方法用于 React,它在 2020 年效果很好。感谢@Anubahav Gupta

npm install react-responsive --save

Then create component:然后创建组件:

import React, { Fragment, Component } from 'react';
import MediaQuery from 'react-responsive';

class MyMediaQuery extends Component {
    render() {
        return (
            <Fragment>
                <div>Device Test!</div>

                <MediaQuery minDeviceWidth={1224}>
                    <div>You are a desktop or laptop</div>
                </MediaQuery>
                <MediaQuery maxDeviceWidth={1224}>
                    <div>You are a tablet or mobile phone</div>
                </MediaQuery>

                <MediaQuery orientation='portrait'>
                    <div>You are portrait</div>
                </MediaQuery>
                <MediaQuery orientation='landscape'>
                    <div>You are landscape</div>
                </MediaQuery>

                <MediaQuery minResolution='2dppx'>
                    <div>You are retina</div>
                </MediaQuery>
            </Fragment>
        );
    }
}

export default MyMediaQuery;

It works as-is on any page loaded but can also be imported into another file with:它可以在任何加载的页面上按原样工作,但也可以通过以下方式导入另一个文件:

import MyMediaQuery from '.newFileName';

Then used anywhere as:然后在任何地方使用:

<MyMediaQuery />

这不是 React 特有的,但这是我的 js 函数:

export const isMobile = () => window.matchMedia && window.matchMedia("(max-width: 480px)").matches
const getNumberDesignRequest = screenWidth => {
  let numberDesignRequest = 20
  if (screenWidth >= 1280 && screenWidth < 1525) {
    numberDesignRequest = 21
  }
  
  return numberDesignRequest
}

const ScreenWidth = () => {
  const [screenWidth, setScreenWidth] = useState(window.innerWidth)

  useLayoutEffect(() => {
    const handleResize = () => {
      const { innerWidth } = window
      setScreenWidth(innerWidth)
    }

    window.addEventListener('resize', debounce(handleResize, 1000))
    return () => window.removeEventListener('resize', handleResize)
  }, [])

  return screenWidth
}

const FuzzySearch = () => {
  const screenWidth = ScreenWidth()
const numberDesignRequest = getNumberDesignRequest(screenWidth)

Tablets has big screens but they act like mobile phones, so if you want to detect touch screen instead of the size of the screen:平板电脑有大屏幕,但它们就像手机一样,所以如果你想检测触摸屏而不是屏幕大小:

const isTouchScreenDevice = () => {
    try{
        document.createEvent('TouchEvent');
        return true;
    }catch(e){
        return false;
    }
}

The solution for this is to check the size of the screen解决办法是检查屏幕的大小

const width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
const MAX_WIDTH_FOR_MOBILE = 900;

Now check the width of the screen with the max width现在用最大宽度检查屏幕的宽度

return (
   width < MAX_WIDTH_FOR_MOBILE ? <Mobile /> : <Desktop />
)

React doesn't do this, React is only the View in MVC. React 不这样做,React 只是 MVC 中的视图。 Determination logic (controlling what SHOULD be viewed) is the role of the Controller.确定逻辑(控制应该查看的内容)是 Controller 的角色。 React doesn't implement a controller but thinks that should be done by the rest of the application, so you should add some other code controlling the context of the React component or even using different components for different devices. React 没有实现控制器,但认为应该由应用程序的其余部分来完成,因此您应该添加一些其他代码来控制 React 组件的上下文,甚至为不同的设备使用不同的组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检测 React 应用程序是否真的在移动菜单操作上被查看 - How to detect if the React app is actually being viewed on mobile menu actions 如何确定设备是否为桌面浏览器? - How do I determine if a device is a desktop browser? 如何强制桌面浏览器以移动模式打开 - How to force desktop browser to open in mobile mode 如何在桌面上模拟移动(android)浏览器 - how to emulate a mobile (android) browser on desktop 如何使用 ReactJs 将网络摄像头流式传输到移动浏览器? - How to stream webcam into mobile browser by using ReactJs? 手机桌面浏览器模拟器 - Desktop Browser Simulators for Mobile 如何使用在桌面浏览器上运行的移动应用程序渲染移动屏幕? - How to render a mobile screen with mobile app running on desktop browser? Google Analytics如何确定“设备类别”(移动设备/平板电脑/桌面设备)? - How does Google Analytics determine “Device Category” (mobile/tablet/desktop)? 如何从浏览器与桌面应用程序通信? - how to communicate with a desktop application from browser? 如何创建仅在从移动设备查看网站时才有效的手风琴盒? - How do I create an accordion box that only works if the site is being viewed from mobile?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM