自学内容网 自学内容网

长按加速- 解决react - setInterval下无法更新问题

最开始直接setInterval里,useState硬写,发现更新不,固定值

换let,发现dom更新不了

正确做法是用ref

并且pc端可以长按的,只是要用onTouchStart,不要用onMouseDown

onTouchStart={handleMouseDown} onTouchEnd={handleMouseUp} onTouchMove={handleMouseUp}

然后我是一个rounded大盒子

盒子里套了一个rounde的absoulte,但是overflow-hidden,和一个正方形的div,这样就会出现竖线进度条。

 <div
      className="py-[6px] px-[12px] rounded-[25px] flex justify-center  items-center gap-[5px] border "
      style={{ border: "1px solid rgba(255,255,255,0.80)" }}
    >
      <div className=" absolute w-full h-full -z-10   overflow-hidden rounded-[25px] ">
        <div
          className={`h-full -z-10  bg-[rgba(255,255,255,0.40)]`}
          style={{ width: `${progress}%` }}
        ></div>
      </div>
      <span onTouchStart={handleMouseDown} onTouchEnd={handleMouseUp} onTouchMove={handleMouseUp}>
        长按跳过
      </span>
      <LongClickIcon />
    </div>

code

 const [progress, setProgress] = useState(0)

  const timerRef = useRef<number>()

  const handleMouseDown = () => {
    timerRef.current = setInterval(() => {
      setProgress((prevProgress) => {
        if (prevProgress === 100) {
          clearInterval(timerRef.current)
          handleClick()
          return 100
        } else {
          return prevProgress + 1
        }
      })
    }, 10)
  }

  const handleMouseUp = () => {
    clearInterval(timerRef.current)
    setProgress(0)
  }

  useEffect(() => {
    return () => {
      setProgress(0)
      clearInterval(timerRef.current)
    }
  }, [])


原文地址:https://blog.csdn.net/StrongerIrene/article/details/140447188

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!