自定义Hooks写表单防抖

import React, { useState, useEffect, useRef } from 'react'

const useDebounce = function (value: any, timeout: number): [any] {
  let [state, setState] = useState(value)
  const refContainer = useRef(false)
  useEffect(() => {
    if (refContainer.current) {
      let someValue = '输入中...'
      setState(someValue)
    } else {
      refContainer.current = true
    }
    let timer = setTimeout(() => setState(value), timeout);
    return () => clearTimeout(timer)
  }, [value, timeout])
  return [state]
}

const City: React.FC = () => {
  const [input, setInput] = useState('');
  const [output] = useDebounce(input, 500)
  const handleInput = (e: any) => {
    setInput(e.target.value)
  }

  return (
    <div>
      <input type="text" value={input} onChange={handleInput} />
      {output}
    </div>
  )
}
发布了254 篇原创文章 · 获赞 200 · 访问量 21万+

猜你喜欢

转载自blog.csdn.net/wu_xianqiang/article/details/103907038