react native实现防抖,TextInput输入实现防抖处理

3,939 阅读2分钟

react natvei 实现防抖 (debounce)

防抖处理是经常会用到的功能,比如处理滚动事件做一些复杂计算,这样就会频繁调用回调函数很容易会造成页面的卡顿,这种情况下,我们更希望把多次计算合并成一次,只操作一个精确点,我们普遍把这种方式称为debounce(防抖)和throttle(节流)。

当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定时间到来之前,又触发了事件,就重新开始延时。也就是说当一个用户一直触发这个函数,且每次触发函数的间隔小于设定时间,那么防抖的情况下只会执行一次。

把防抖封装成一个插件,每次使用只需要调用即可。

// debounce.js  防抖封装

let timeout = null
const debounce = (cb, wait = 500) => {
  if (timeout !== null) clearTimeout(timeout)
  timeout = setTimeout(() => {
    timeout = null
    cb && cb()
  }, wait);
}
module.exports = debounce;

我们可以放在App.js全局调用,省掉每次都需要import导入

 // App.js

 // 在app.js引入文件
import debounce from './src/utils/debounce'; 

// 定义一个全局变量debounce
global.debounce = debounce // 防抖 默认1000毫秒 使用方法 debounce(() => this.handle())

我们也可以在文件中单独引用,直接在页面头部引用

// home.js
import debounce from './src/utils/debounce';   // 引入

使用方法

注意:当前的debounce已经在App.js定义成全局变量,如果未定义需要单独引用
import React, { Component } from 'react'
import {
  Text,
  View,
  TextInput
} from 'react-native'

// 防抖测试
export default class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      text: '',
      changeText: ''
    }
  }

  // 数据处理
  requstData = () => {
    this.setState({
      changeText: this.state.text
    })
  }

  inputValue = (text) => {
    this.setState({
      text: text
    })

    // 使用防抖
    debounce(() => this.requstData(), 500)
  }

  render() {
    return (
      <View style={{ flex: 1 }}>
        <Text style={{ fontSize: 20, color: '#000', fontWeight: 'bold' }}>防抖</Text>
        <TextInput
          style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
          onChangeText={(text) => this.inputValue(text)}
          value={this.state.text}
        />
        <Text style={{ marginTop: 50, fontSize: 20, color: 'blue', fontWeight: 'bold' }}>
          防抖效果:{this.state.changeText}
        </Text>
      </View>
    );
  }
}


效果

防抖