在React.js中为移动和桌面端使用两个不同的导航组件。

huangapple go评论68阅读模式
英文:

Having two different navigation components for mobile and for desktop in React.js

问题

我一直在考虑是否应该在移动设备和桌面设备上分别使用两个不同的导航栏,并有条件地渲染其中一个,或者是否应该全程使用查询以及在JavaScript本身上进行更多的条件渲染,你有什么建议?
我的导航栏也根据用户是否已登录而有所不同。
提前感谢。

英文:

I've been thinking about wether I should have two different navigation bar one for mobile and for deskptop and just conditionally render one or another, Or if I should just go all the way with queries and more conditional render on the javascript itself, what would you suggest?
My navigation bar also varies on wether the user is Logged in or Not.
Thanks in advance.

答案1

得分: 1

我建议使用媒体查询。如果你在移动和桌面上渲染导航栏,你将需要JS逻辑来确定你在哪个视口上。如果你的React应用程序总是需要首先在客户端确定它在哪个视口上,可能会导致不美观的重新加载或闪烁。
你需要像useEffect这样的钩子来确定你在哪个视口上。然而,如果你的所有React组件都有服务器端渲染,那么这不是很高效的方法。看一下TailwindCss,那里很容易使用媒体查询。或者查看你喜欢的网站,它们也有不同版本的导航栏,可以了解它们的做法。
如果你想根据用户是否已登录来自定义导航栏,我建议使用createContext/useContext。

英文:

I would suggest using media queries. If you render navigation for mobile and desktop, you will need JS logic to determine which viewport you are on. If your React application always needs to figure out which viewport it is on first on the client-side, it could result in unsightly reloading or flashing.
You would need hooks like useEffect to determine which viewport you are on. However, if all your React components have server-side rendering for example, then this is not very efficient. Have a look at TailwindCss, there it is easy you use media queries. Or check your favorite websites that also have different versions of navigations to figure out their way of doing it.
If you want to customize the navigation depending on whether the user is logged in or not, I would recommend usin createContext/useContext .

huangapple
  • 本文由 发表于 2023年4月19日 22:46:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76055879.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定