阻止事件冒泡的使用场景

107 阅读1分钟

阻止事件冒泡

image.png

  • 如图,点击箭头滚动,点击图片会进入详情页,但是我们监听的是整个 item 的点击,我们如何让点击箭头的时候不进入详情页?

    • 使用阻止冒泡事件即可
    function controlClickHandle(isNext: boolean, event: any) {
        isNext ? carouselRef.current?.next() : carouselRef.current?.prev()
    
        // 1.如果点击下一个 index+1 上一个-1
        let newIndex = isNext ? selectIndex + 1 : selectIndex - 1
        // 2.如果小于0 index设为最后一个
        const len = itemData.picture_urls.length
        if (newIndex < 0) newIndex = len - 1
        // 3.如果大于最后一个 index设为第一个
        if (newIndex > len - 1) newIndex = 0
        setSelectIndex(newIndex)
    
        // 4.阻止事件冒泡
        event.stopPropagation()
      }
    
    {/* 滚动箭头 */}
          <div className={style.control}>
            <div
              className={style.left}
              onClick={(e) => controlClickHandle(false, e)}
            >
              <IconArrowLeft width={20} height={20} />
            </div>
            <div
              className={style.right}
              onClick={(e) => controlClickHandle(true, e)}
            >
              <IconArrowRight width={20} height={20} />
            </div>
          </div>