Skip to content

React - Unable to preventDefault inside passive event listener #11

@gaoryrt

Description

@gaoryrt

最近在用 react,hooks 配合 functional component 写起来非常的有禅意。

前两天遇见这个需求:
需要在自定义 prompt 出来的时候禁止页面滑动。

image

自然想到在 onTouchMove 和 onTouchStart 的时候去 preventDefault,
但是 Chrome 直接报错了:
Unable to preventDefault inside passive event listener

如果是 addEventListener('touchstart', fn, {passive: true}) 的 fn 里面尝试 preventDefault 就会报这个错。
事件监听时的 passive option 有什么用呢,能大幅提高滚动性能,前提是产品设计保证了不会阻止滚动。
所以应该是 react 在设置 onTouch* 系列监听的时候,设置了这个 passive
查了一下,原来是 chrome 56 开始的一个 feature

With this change touchstart and touchmove listeners added to the document will default to passive:true (so that calls to preventDefault will be ignored)..

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions