javascript - React onWheel 处理程序无法阻止Default,因为它是一个被动事件监听器
问题描述
我正在尝试覆盖组件上的 Ctrl+scroll 行为,但它不适用于 error [Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See <URL>
。我想我可以使用主动监听器,那么有没有办法通过 React 来指定呢?请注意,我需要访问和修改onWheel
.
const onWheel = (e: React.WheelEvent): void => {
if (e.altKey) {
e.preventDefault();
// Error
} else if (e.ctrlKey) {
e.preventDefault();
// Error
}
};
...
return (<div className={styles["workspace"]} onWheel={onWheel}>
stuff
</div>);
解决方案
有点晚了,但也许它可以帮助别人。
问题是React 默认使用被动事件处理程序,带有 wheel、touchstart 和 touchmove 事件——换句话说,你不能stopPropagation
在它们中调用。
如果要使用非被动事件处理程序,则需要使用refs并手动添加/删除事件处理程序,如下所示:
class MyComponent extends React.Component {
myRef = React.createRef();
componentDidMount() {
// IMPORTANT: notice the `passive: false` option
this.myRef.current.addEventListener('wheel', this.handleWheel, { passive: false });
}
componentWillUnmount() {
this.myRef.current.removeEventListener('wheel', this.handleWheel, { passive: false });
}
handleWheel = (e) => {
e.stopPropagation();
// ...
}
// ...
}
应该与钩子类似。
推荐阅读
- reactjs - Mobx awkward case. if i console.log(userStore) then it updates component
- tabulator - 制表符复选框多选
- visual-studio - 缺少选项值:installPath
- javascript - 单击弹出窗口后显示麦克风权限
- sql - SQL - 连接两个表,但仅通过左表出现来获取连接列的平均值
- sql-server - 我用 sql 查询生成 excel 表,但它只在 93 版本中生成,我怎样才能让它到 2013 版本?
- dependency-injection - Dagger 2 - proxyProvide 方法的目的是什么?
- python - 如何拥有一个非常局部的全局变量?
- data-binding - UWP如何使用绑定ListView的选定项中的更改来更新绑定的TextBox
- ruby-on-rails - 在 Dokku 实例上安装 PgBouncer?