简体   繁体   English

Next.js 根据设备渲染组件

[英]Next.js Render components depending on device

I'm creating a component that has 2 different variants (one for mobile, another one for desktop).我正在创建一个具有 2 个不同变体的组件(一个用于移动设备,另一个用于桌面设备)。 The logic is the same, but HTML structure and CSS - totally different.逻辑相同,但 HTML 结构和 CSS 完全不同。 I decided to split those views into separate components.我决定将这些视图拆分为单独的组件。

In my project, I use ISR so the page will rebuild every one minute.在我的项目中,我使用 ISR,因此页面将每隔一分钟重建一次。

I'm trying to sort out the thing with showing a proper component depending on the device - how to do it correctly (note that it's a static generated page)?我正在尝试通过根据设备显示适当的组件来解决问题-如何正确执行(注意它是 static 生成的页面)?

I tried to use media queries, but it looks like when I render both components, I have a problem with duplicated HTML IDs.我尝试使用媒体查询,但看起来当我渲染两个组件时,我遇到了重复的 HTML ID 的问题。

Thanks!谢谢!

If page generated at build time, you don't have much options here.如果页面是在构建时生成的,那么您在这里没有太多选择。

First option would be to assign different id s to elements and hide one with css.第一个选项是为元素分配不同的id并使用 css 隐藏一个。 You then can determine in runtime which one is visible if needed.然后,您可以在运行时确定哪个是可见的(如果需要)。 Second option, is to render component only on client side after hydration.第二种选择,是在水化后仅在客户端渲染组件。 This is assuming that you use client side javascript.这是假设您使用客户端 javascript。 Then you can opt out of static generation for this particular page or set of pages.然后,您可以为该特定页面或页面集选择退出 static 生成。

Here is one more thing you can try, depending on your markup.这是您可以尝试的另一件事,具体取决于您的标记。 If you have markup like this:如果你有这样的标记:

<div id="my-id" class="big"><!-- big screen content here --></div>
<div id="my-id" class="small"><!-- small screen content here --></div>

You can turn it into this:你可以把它变成这样:

<div id="my-id">
  <div class="small"><!-- big screen content here --></div>
  <div class="small"><!-- small screen content here --></div>
</div>

This way you will have single id and two different contents.这样,您将拥有一个id和两个不同的内容。

Opinion part that may not align with your goals:可能与您的目标不一致的意见部分:

Best way to do it would still be one set of markup with different styles for different window sizes.最好的方法仍然是一组具有不同 styles 的标记,用于不同的 window 大小。 This way users will see appropriate version after they resize their browser window or zoom in. And users who can't use pointer device will not loose their focus after resizing browser window.这样用户在调整浏览器 window 大小或放大后将看到适当的版本。并且不能使用指针设备的用户在调整浏览器 window 大小后不会失去焦点。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM