React JS 中的设备检测和响应式设计
在本文中,我们将了解如何根据设备呈现页面,但无需使用if-else 子句。为此,我们将使用react-device-detect 包。此功能可以帮助我们创建响应式网页,无需使用任何媒体查询。所以,让我们开始吧。
示例
首先创建一个 React 项目 -
npx create-react-app tutorialpurpose
转到项目目录 -
cd tutorialpurpose
下载react-device-detect 包 -
npm install react-device-detect --save
我们将使用此包添加默认媒体查询或默认条件渲染,这些查询或条件渲染已预制在包内。
在App.js 中添加以下代码行 -
import {
BrowserView,
MobileView,
isBrowser,
isMobile,
} from "react-device-detect";
export default function App() {
return (
<>
<BrowserView>
<h1> This is rendered only in browser </h1>
</BrowserView>
<MobileView>
<h1> This is rendered only on mobile </h1>
</MobileView>
</>
);
}说明
<BrowserView> 内部的元素仅显示在笔记本电脑或 PC 上。
类似地,<MobileView> 内部的元素仅显示在手机上。
IsMobile 和 IsBrowser 可以与 if-else 子句配合使用。
输出
浏览器视图

移动视图

广告
数据结构
联网
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP