根据设备类型呈现不同组件(最佳实践)?

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

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.

&lt;button
      onMouseEnter={handleModalOpen}
      onMouseLeave={handleModalClose}
      className=&quot;info-button&quot;
    &gt;
      info
    &lt;/button&gt;

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(() =&gt; {
const update = (e) =&gt; {
  setX(e.x);
  setY(e.y);
};
window.addEventListener(&quot;mousemove&quot;, update);
window.addEventListener(&quot;touchmove&quot;, update);
return () =&gt; {
  window.removeEventListener(&quot;mousemove&quot;, update);
  window.removeEventListener(&quot;touchmove&quot;, 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 &#39;react-device-detect&#39;;

然后像其他条件一样使用:

 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 &#39;react-device-detect&#39;;

and use like any other conditional:

 if (isMobile) {
  // do something
}

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

发表评论

匿名网友

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

确定