【问题标题】:Throttling using Lodash in React Native在 React Native 中使用 Lodash 进行节流
【发布时间】:2018-01-29 12:02:58
【问题描述】:

我正在尝试使用 lodash.throttling 来限制可触摸突出显示中 onPress 调用的数量,使用以下代码,但没有一个有效:

 <TouchableHighlight
       onPress={throttle(this.onPressHandler,5000,{leading:true, trailing:false})}>

 <TouchableHighlight
       onPress={()=>throttle(this.onPressHandler,5000,{leading:true, trailing:false})}>

但是,当我将 console.log 放入“onPressHandler”函数时,即使我快速连续点击 TouchableHighlight,我也会看到该函数被多次调用。

我错过了什么?

【问题讨论】:

标签: react-native lodash


【解决方案1】:

感谢 Sebastien 对this 问题的回答,我得到了这个工作

答案是关于 React.js,但 React Native 的概念也很相似。

我将以下代码添加到构造函数中,并将 onPress 直接映射到 onPressHandler

this.onPressHandler = throttle(this.onPressHandler, 5000, {leading:true, trailing:false});

【讨论】:

    【解决方案2】:

    尝试在您的onPress 方法上添加callback,这样它就不会被自动调用。

    <TouchableHighlight
        onPress={() => throttle(this.onPressHandler,5000,{leading:true, trailing:false})}>
    

    【讨论】:

      【解决方案3】:

      另一种解决方案是使用此包中的&lt;Throttle&gt; 组件:https://github.com/gmcquistin/react-throttle。它在 React Native 应用程序中运行良好(我目前正在我的一个应用程序中使用它)。

      用法:

      import { Throttle } from 'react-throttle';
      
      <Throttle time="5000" handler="onPress">
          <TouchableHighlight onPress={this.onPressHandler} />
      </Throttle>
      

      【讨论】:

        猜你喜欢
        • 2021-11-30
        • 2017-05-03
        • 1970-01-01
        • 1970-01-01
        • 2017-11-07
        • 1970-01-01
        • 1970-01-01
        • 2023-01-03
        • 2018-05-04
        相关资源
        最近更新 更多