我正在尝试覆盖组件上的 Ctrl+滚动行为,但它无法处理错误 [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 uses passive event handlers by default使用 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();
// ...
}
// ...
}
应该与钩子(Hook)类似。
关于javascript - React onWheel 处理程序无法阻止Default,因为它是一个被动事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63663025/