1. 程式人生 > 實用技巧 >React 實現input輸入框的防抖和節流

React 實現input輸入框的防抖和節流

React 實現input輸入框的防抖和節流

1.為什麼使用防抖和節流
對於頻繁觸發的事件 比如keydown keyup事件 當頻繁點選時候 會多次觸發事件 頁面出現卡頓 影響效能

2.函式防抖(debounce):間隔時間內只執行一次 函式節流(throttle):間隔時間內執行

3.使用場景
函式防抖:搜尋框等
函式節流:滑鼠不斷點選事件等

4.目的

提升效能 提高使用者體驗

5.用react實現防抖和節流

剛好react腳手架是集成了lodash的

import throttle from 'lodash/throttle';

export default class Search extends Component {
    constructor(props) {
      super(props)
      this.handleSearch = throttle(this.handleSearch, 1000);//這裡的間隔就是每xx時間內只執行一次該函式
    }
    handleSubmit = (e) => {
        e.preventDefault();
        this.handleSearch();
    }
    handleSearch = () => {
    ...
    }
    render() {
        return (
            <form onSubmit={this.handleSubmit}><form>
        )
    }
}