Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

封装 LongPressable,监听长按事件 #7

Open
heycn opened this issue May 3, 2023 · 0 comments
Open

封装 LongPressable,监听长按事件 #7

heycn opened this issue May 3, 2023 · 0 comments

Comments

@heycn
Copy link
Owner

heycn commented May 3, 2023

组件封装

LongPressable.tsx

import type { ReactNode, TouchEvent } from 'react'
import { useRef } from 'react'

type Props = {
  children: ReactNode
  onEnd?: () => void
}
export const LongPressable: React.FC<Props> = (props) => {
  const { children, onEnd } = props
  const touchTimer = useRef<number>()
  const touchPosition = useRef<{ x?: number; y?: number }>({ x: undefined, y: undefined })
  const onTouchStart = (e: TouchEvent) => {
    touchTimer.current = window.setTimeout(() => {
      onEnd?.()
    }, 500)
    const { clientX: x, clientY: y } = e.touches[0]
    touchPosition.current = { x, y }
  }
  const onTouchMove = (e: TouchEvent) => {
    const { clientX: newX, clientY: newY } = e.touches[0]
    const { x, y } = touchPosition.current
    if (x === undefined || y === undefined) { return }
    const distance = Math.sqrt((newX - x) ** 2 + (newY - y) ** 2)
    if (distance > 10) {
      window.clearTimeout(touchTimer.current)
      touchTimer.current = undefined
    }
  }
  const onTouchEnd = (e: TouchEvent) => {
    if (touchTimer.current) {
      window.clearTimeout(touchTimer.current)
      touchTimer.current = undefined
    }
  }
  return (
    <div onTouchStart={onTouchStart} onTouchMove={onTouchMove} onTouchEnd={onTouchEnd}>
      {children}
    </div>
  )
}

使用

<LongPressable onEnd={() => console.log(long pressable!)}>
  <h1>long pressable me!</h1>
</LongPressable>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant