Jef*_*che 13 javascript dom dom-events reactjs
我试图覆盖组件上的 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>);
Run Code Online (Sandbox Code Playgroud)
joh*_*odo 21
有点晚了,但也许对其他人有帮助。
问题是,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();
// ...
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
应该和钩子类似。
| 归档时间: |
|
| 查看次数: |
11081 次 |
| 最近记录: |