How can React prevent accidental touches during scrolli…

In React, you can use the preventDefault() method to prevent accidental touches during scrolling. The specific method is as follows:

  1. initial Y coordinate of touch
  2. movement is occurring
constructor(props) {
  super(props);
  this.touchStartY = 0;
  this.isScrolling = false;
}
  1. Next, record the y-axis value of the touch event when the sliding starts.
handleTouchStart = (event) => {
  this.touchStartY = event.touches[0].clientY;
};
  1. Then, during the sliding process, determine if the distance of the slide exceeds a certain threshold, and if it does, prevent the default sliding behavior.
handleTouchMove = (event) => {
  const touchCurrentY = event.touches[0].clientY;
  const touchDistanceY = touchCurrentY - this.touchStartY;
  
  if (Math.abs(touchDistanceY) > 10 && !this.isScrolling) {
    event.preventDefault();
    this.isScrolling = true;
  }
};
  1. initial touch Y position
  2. Scrolling
handleTouchEnd = () => {
  this.touchStartY = 0;
  this.isScrolling = false;
};
  1. Bind the above defined methods to the corresponding scroll events in the render method of the component.
render() {
  return (
    <div
      onTouchStart={this.handleTouchStart}
      onTouchMove={this.handleTouchMove}
      onTouchEnd={this.handleTouchEnd}
    >
      {/* 组件内容 */}
    </div>
  );
}

By utilizing the above methods, it is possible to prevent accidental touch issues from occurring during the sliding process.

bannerAds