【问题标题】:Is there a way to prevent an event to be triggered based on a condition?有没有办法防止根据条件触发事件?
【发布时间】:2021-09-26 00:28:54
【问题描述】:

我正在构建一个 ReactJS 应用程序,并且我有一个在单击后调用的函数,但是我希望仅当屏幕宽度大于 1200 像素时才触发此单击事件。

例如,在下面的代码中,我在subContainer 元素中添加了一个onClick 事件,如果屏幕宽度小于1200 像素,我想阻止这个onClick 被触发。

有没有办法在不使用监听器的情况下做到这一点?

我知道我可以使用侦听器并设置条件来确定是否侦听此事件;我也知道我可以在函数内设置条件并阻止执行逻辑;而且我还可以创建两个不同的 JSX 元素(一个没有事件)并根据我的条件渲染一个或另一个。但我想要的是保留元素上的onClick(没有addEventListener)并防止它被触发

应该是这样的:<div screenWidth > 1200 ? onClick="..." : null>Test</div>。当然,这是行不通的。

这可能吗?

附:请记住,我使用的是 React,这段代码只是一个示例。

const test = () => {
  console.log('Test')
}
.subContainer {
  width: 100px;
  height: 20px;
  background-color: red;
  color: white;
  text-align: center;
  cursor: pointer;
}
<div class="container">
  <div class="subContainer" onClick="test()">Test<div>
</div>

【问题讨论】:

  • 可能类似于onClick={window.screen.width &gt; 1200 ? test() : () =&gt; console.log('Not true')} 或在您的测试函数内部if(window.screen.width &gt; 1200) do stuff
  • 是的,我能做到。但我想要的是防止事件被触发而不是改变将被调用的内容。
  • 我认为这个答案:stackoverflow.com/a/68421971/10213537,可能是更好的解决方案,条件是window.screen.width &gt; 1200

标签: javascript reactjs events event-handling dom-events


【解决方案1】:

也许是这样的:

import "./styles.css";

export default function App() {
  console.log(window.screen.width);
  let myCondition = window.screen.width > 1200;
  console.log(myCondition);
  const clickThis = () => {
    console.log("hello");
  };

  return (
    <div className="App">
      <button
        onClick={ myCondition ? clickThis : null}
      >
        Hello CodeSandbox
      </button>
    </div>
  );
}

另外,显然它是 window.screen.width 而不是 window.screenWidth。

Codesandbox

【讨论】:

  • 我看到如果myCondition 为false,则不会调用该函数,但无论如何不会触发event
  • 抱歉,我尝试了多种方法。修改为我的第一个答案。这种方式不会触发任何事情。
【解决方案2】:

你可以使用钩子来监听窗口大小并根据onClick内部的宽度传递函数

function App() {
  const size = useWindowSize();
  return (
    <div class="container">
      <div class="subContainer" onClick={size.width > 1200 ? test : null}>
        Test
      </div>
    </div>
  );
}

这里是简单的useWindow hook的链接

【讨论】:

  • OP想要屏幕宽度,这是与window.innerWidth和innerHeight不同的属性,useWindowSize钩子是不必要的,因为屏幕宽度不会改变。
  • 我在获取屏幕或窗口宽度方面没有问题,我只需要知道这个null 是否阻止事件被触发?
【解决方案3】:

根据this post 将属性设置为 false 会导致响应从 HTML 中省略它,这可能会导致事件开始时不被调用,所以也许使用onClick={window.screen.width &gt; 1200 ? function() : false} 是最好的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-22
    • 2022-08-04
    • 1970-01-01
    • 2020-10-10
    • 2011-01-23
    • 2022-10-13
    • 2021-02-11
    相关资源
    最近更新 更多