仍在应用移动设备悬停状态上元素上的onClick事件

问题描述 投票:1回答:1

除非我一直在寻找错误的东西,否则我似乎无法在网上找到任何与React相同的问题?

我有一个按钮(锚标签)有一个onClick事件。当触发onClick事件时,它调用loadMore()函数,该函数进行API调用并更新某些状态。

但是,当我单击按钮时,在移动设备上(不是桌面上的移动分辨率!),onClick事件会起作用并返回预期的内容,但是它会在按钮上应用悬停状态。对于按钮悬停状态,我应用了背景颜色

悬停状态将一直持续到我点击屏幕上的任何其他位置。所以背景颜色一直持续到我点击之后。

现在,这不是完全可取的。为什么会发生这种情况,我是如何预防的呢?

Here is my Button Component

const Button = props => {
  const buttonDisabledClass = props.disabled ? "Button--disabled " : "";
  const hiddenClass = props.hidden ? "Button--hidden " : "";
  const modifierClass = props.modifier ? props.modifier : "";

  return (
    <>
      <a
        onClick={!props.disabled ? props.onClick : undefined}
        className={
          "Button " + buttonDisabledClass + hiddenClass + modifierClass
        }
      >
        {props.children}
        {props.buttonText ? (
          <span
            className={`Button-text ${
              props.buttonMobileText ? "Button-desktopText" : ""
            }`}
          >
            {props.buttonText}
          </span>
        ) : null}
        {props.buttonMobileText ? (
          <span className="Button-mobileText">{props.buttonMobileText}</span>
        ) : null}
      </a>
    </>
  );
};

Here is the parent component

父组件导入Button组件并具有发出API请求的功能(这里仅以模拟的组件为例)

function App() {
  const [number, setNumber] = useState(0);

  /*simulate http request*/
  const ttl = 500;
  const loadMore = () => {
    const timeout = setTimeout(() => {
      setNumber(number + 1);
    }, ttl);
    return () => {
      clearTimeout(timeout);
    };
  };

  return (
    <div className="App">
      {number}
      <Button
        key={"loadMoreBtn"}
        modifier="Button--loadMore Button--Inline"
        onClick={() => loadMore()}
      >
        Load More
      </Button>
    </div>
  );
}

那么,我怎么能这样做,所以点击移动设备不会注册悬停,但仍然有悬停工作在桌面设备上,因为它是目前的?

如果你想为自己测试一下,我有一个CODESANDBOX

这是一个link供您在移动设备上测试。

默认情况下,该按钮为橙色,悬停时为灰色。在移动设备上,当您点击... enter image description here时会发生这种情况

任何帮助将不胜感激!

javascript css reactjs hover mousehover
1个回答
1
投票

您可以使用CSS中的媒体查询覆盖移动设备上的悬停效果:

@media only screen and (min-resolution: 117dpi) and (max-resolution: 119dpi), only screen and (min-resolution: 131dpi) and (max-resolution: 133dpi), only screen and (min-resolution: 145dpi) and (max-resolution: 154dpi), only screen and (min-resolution: 162dpi) and (max-resolution: 164dpi), only screen and (min-resolution: 169dpi) {
  .Button:hover {
    background-color: #ee4900 !important;
  }
}

要么

@media (hover: none) {
  .Button:hover {
    background-color: #ee4900 !important;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.