html React:为什么只有在使用Chrome浏览器时,我的移动的幻灯片显示的灵敏度才会被搞砸?

nwlls2ji  于 12个月前  发布在  React
关注(0)|答案(1)|浏览(124)

我在React Web应用程序上有一个carousel组件。它在Firefox上运行得很好,但是在Chrome中,当我在移动的上向下滑动页面时,它会认为我在做水平滑动,并在幻灯片上切换幻灯片。我正在使用一个名为react-material-ui-carouse的库,它唯一可用的滑动 prop 是将幻灯片功能设置为true或false。我在文档中找不到任何关于调整幻灯片灵敏度的内容。有没有一个合理的方法来解决这个问题,或者我最好不要使用这个库?Link到网站,如果你想尝试它在移动的,看看我的意思。

幻灯片.jsx

function Slideshow() {
  const fadeImages = [
    {
      src: "/images/allie-pic.webp",
      title: "First Slide",
      caption:
        "Slide1",
    },
    {
      src: "/images/image-2.jpg",
      title: "Second Slide",
      caption:
        "Slide2",
    },
    {
      src: "/images/image-3.webp",
      title: "Third Slide",
      caption:
        "Slide3",
    },
  ];

  return (
    <Carousel
      swipe={true}
      autoPlay={false}
      fullHeightHover={false}  
     
    >
      {fadeImages.map((img, i) => (
        <Item key={i} img={img} />
      ))}
    </Carousel>
  );
}

function Item({ img }) {
  return (
    <Stack alignItems="center">
      <Typography variant="h1">
        {img.title}
      </Typography>
      <Typography variant="body1">{img.caption}</Typography>
      <img     
        src={img.src}
      ></img>
    </Stack>
  );
}
export default Slideshow;
xytpbqjk

xytpbqjk1#

似乎react-material-ui-carousel库中水平滑动的灵敏度或触摸处理可能不适合所有用例,特别是当用户的意图是向下或向上滚动时。

自定义事件处理:您可以尝试向组件添加自定义触摸事件侦听器,以区分垂直滑动(滚动)和水平滑动。如果垂直移动明显大于水平移动,则可以阻止注册水平滑动。

这里有一个非常基本的例子:

function Slideshow() {
    const carouselRef = useRef(null);

    useEffect(() => {
        let startX = 0;
        let startY = 0;

        const handleTouchStart = (e) => {
            startX = e.touches[0].clientX;
            startY = e.touches[0].clientY;
        };

        const handleTouchMove = (e) => {
            const moveX = e.touches[0].clientX - startX;
            const moveY = e.touches[0].clientY - startY;

            if (Math.abs(moveY) > Math.abs(moveX)) {
                e.preventDefault();
                e.stopPropagation();
            }
        };

        const carousel = carouselRef.current;

        if (carousel) {
            carousel.addEventListener('touchstart', handleTouchStart);
            carousel.addEventListener('touchmove', handleTouchMove);
        }

        return () => {
            if (carousel) {
                carousel.removeEventListener('touchstart', handleTouchStart);
                carousel.removeEventListener('touchmove', handleTouchMove);
            }
        };
    }, []);

    return (
        <div ref={carouselRef}>
            <Carousel /* ... other props ... */>
                {/* ... items ... */}
            </Carousel>
        </div>
    );
}

The idea here is to compare the x and y movements in the touchmove event. If the y movement (vertical) is greater, we prevent the event from propagating, which should theoretically prevent the horizontal swipe.

相关问题