英文:
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 .
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论