英文:
Render different component based on device type (best practice)?
问题
我有一个用于构建UI的按钮。
<button
onMouseEnter={handleModalOpen}
onMouseLeave={handleModalClose}
className="info-button"
>
info
</button>
当你鼠标悬停在按钮上时,它会在光标位置打开一个带有一些信息的模态框。在移动设备上,通过轻触也能实现。这是我用来获取光标位置的代码:
useEffect(() => {
const update = (e) => {
setX(e.x);
setY(e.y);
};
window.addEventListener("mousemove", update);
window.addEventListener("touchmove", update);
return () => {
window.removeEventListener("mousemove", update);
window.removeEventListener("touchmove", update);
};
}, [setX, setY]);
我想要提供通过点击按钮打开一个新页面查看更多信息的选项,然而这在移动设备上会产生问题,因为点击导航和鼠标悬停(或在这种情况下是轻触)发生了冲突。
我想知道是否有一种方式可以为移动设备渲染类似的组件?这样我就可以将onClick函数移到模态框上,而不是按钮上。
英文:
I have a button for a UI i'm building.
<button
onMouseEnter={handleModalOpen}
onMouseLeave={handleModalClose}
className="info-button"
>
info
</button>
when you mouse over the button it opens a modal at the cursor position with some info.
On mobile it works with a tap. Here's the code i'm using to get the cursor position:
useEffect(() => {
const update = (e) => {
setX(e.x);
setY(e.y);
};
window.addEventListener("mousemove", update);
window.addEventListener("touchmove", update);
return () => {
window.removeEventListener("mousemove", update);
window.removeEventListener("touchmove", update);
};
}, [setX, setY]);
I want to also have the option to click the button to open a new page with more info, however this creates an issue on mobile as the click to navigate and mouseover (or tap in this case) are conflicting.
I'm wondering if there's a way to render a similar component for mobile? so that I can move the onClick function to the modal instead of the button.
答案1
得分: 0
对于那些仍然感兴趣的人,我找到了一个解决方案。
这个软件包:
react device detect
它提供了一堆条件,可以检查很多不同的浏览器、操作系统和设备:
只需导入你需要的选择器:
import { isBrowser, isMobile } from 'react-device-detect';
然后像其他条件一样使用:
if (isMobile) {
// 做某事
}
英文:
For those still interested I found a solution.
this package:
react device detect
it provides a bunch of conditions which check for loads of different browsers, OSes and devices:
just import the selectors you need:
import { isBrowser, isMobile } from 'react-device-detect';
and use like any other conditional:
if (isMobile) {
// do something
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论