美文网首页
react-native 防抖

react-native 防抖

作者: Biao_349d | 来源:发表于2023-10-27 15:08 被阅读0次
    1. 类组件中使用

    import debounce from 'lodash.debounce'

    class Pagination extends React.PureComponent<any, any> {
      constructor(props: any) {
        super(props)
        this.handlePrev = debounce(this.handlePrev, 1000, {
          leading: true,
          trailing: false
        })
      }
    
    handlePrev  = () => {}
    
    
    1. 在函数式中使用
      import debounce from 'lodash.debounce'
    function Home(){
    const   haldeNext = useCallback(debounce(() => {}, 200), [])
      return <></>
    }
    
    1. 自定义防抖
    import { useRef } from 'react'
    
    /* fn (Function): 要防抖动的函数。
    [delay=0] (number): 需要延迟的毫秒数。
    [options=] (Object): 选项对象。
    [options.leading=false] (boolean): 指定在延迟开始前调用。
    [options.trailing=true] (boolean): 指定在延迟结束后调用
    */
    function useDebounce(fn: any, delay: any, options: { leading?: boolean; trailing?: boolean } = { leading: false, trailing: true }) {
      const { current } = useRef<any>({
        timer: null,
        dateTime: null
      })
      function f(...args: any[]) {
        const endTime = new Date().getTime()
        if (current.dateTime && options.leading && endTime - current.dateTime < delay) {
          return false
        } else if (options.leading) {
          current.dateTime = new Date().getTime()
          fn.bind(undefined, ...args)()
        }
        if (options.trailing) {
          if (current.timer) {
            clearTimeout(current.timer)
          }
          current.timer = setTimeout(fn.bind(undefined, ...args), delay)
        }
      }
    
      return f
    }
    
    export default useDebounce
    
    

    使用自定义防抖

    
        const onActionButton = useDebounce(
          async (item: any) => {
            console.log('item', item)
          },
          1000,
          {
            leading: true,
            trailing: false
          }
        )
    

    相关文章

      网友评论

          本文标题:react-native 防抖

          本文链接:https://www.haomeiwen.com/subject/lpeeidtx.html