基于Gatsby中屏幕尺寸的切换布局

问题描述 投票:1回答:1

我正在使用Gatsby构建一个Web应用程序,需要在移动浏览器中加载使用移动ui库构建的单独布局,并在桌面浏览器中打开时使用另一个ui库进行不同布局。

我应该如何在根(app)组件级别实现此目的?

谢谢

reactjs gatsby
1个回答
1
投票

我想你可以尝试使用wrapPageElement in gatsby-browser.js and gatsby-ssr.js,根据浏览器高度返回不同的布局:

const React = require("react")
const Layout = ...
const MobileLayout = ...

exports.wrapPageElement = ({ element, props }) => {

   // a made up hook to detect browser size, implement your own
   const isMobile = useDetectMobile()

  return (
    isMobile 
      ? <MobileLayout {...props}>{element}</MobileLayout> 
      : <Layout {...props}>{element}</Layout>

  )
}

但这很棘手,因为在服务器端生成期间,您需要一个默认布局,这可能(或可能不会)导致错误行为?我不确定。

一个安全的选择是为您的应用程序生成移动版本和桌面版本,然后在gatsby-browser中检测浏览器大小/类型并相应地重定向。

© www.soinside.com 2019 - 2024. All rights reserved.