当前位置:   article > 正文

react频繁使用的js(input防抖请求、节流)_js react输入框防抖

js react输入框防抖

react频繁使用的js(input防抖请求)

input的防抖请求

import React, { useState, useEffect, useCallback } from "react";
import { Input } from "antd";
import SearchDeptID from "styled-components";
import { debounce } from "lodash";
export default function SearchDept(props) {
  const [keyword, setKeyword] = useState("");

  // input使用防抖
  const keywordDebounce = useCallback(debounce((val)=>{
    console.log('val',val);
  }, 300),[])
  const inputChange = (event) => {
    const value = event.target.value;
    setKeyword(value);
    keywordDebounce(value);
  }

  return (
    <SearchDeptWrap>
      <Input
        placeholder="请输入"
        className="ipt"
        value={keyword}
        onChange={inputChange}
      />
    </SearchDeptWrap>
  );
}
const SearchDeptWrap = SearchDeptID.div`
`;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

节流 提交的节流或者点击按钮等节流

节流 code


import { throttle } from 'lodash';
import React, { useCallback, useState } from 'react';

export default function App(props) {
  const [count, setCount] = useState(0);

  const throttleFunc = useCallback(
    throttle(() => {
      console.log('throttleFunc');
      setCount((prevCount) => prevCount + 1);
    }, 1000),
    []
  );

  const addCount = () => {
    console.log('addCount');
    throttleFunc();
  };

  return (
    <div className='content'>
      count-{count}
      <button onClick={addCount}>addCount</button>
    </div>
  );
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

节流 效果

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/139008?site
推荐阅读
相关标签
  

闽ICP备14008679号