使用 React Hooks 控制触摸事件

Throttle touch event with React Hooks

我有一个 div,当我向上拖动手指时,我希望 div 中的数字增加。

当我向下拖动手指时,我希望里面的数字减少。

使用触摸事件实现起来相当简单。

codesandbox 在这里 - 我试图让它尽可能简单! Codesandbox

我遇到的问题是事件触发得非常快,这使得很难找到特定的数字。使用 lodash 节流函数来节流事件会很棒,但在这里我遇到了问题!没有任何反应!

我试过像这样使用 useRef:

const throttledPosition = useRef(throttle(touchPosition => touchPosition, 200)).current;

同样,没有任何反应。

第 1 部分 - 限制事件处理程序

您的第一个问题是由您使用 _.throttle() 的方式引起的,它最好包含在您的事件处理程序回调中。

请查看 lodash.throttle() docs 中的示例以供参考。

另请参阅 ,它可能会让您更深入地了解在 React Hooks 中使用 throttle。

关键的变化是用throttle包装事件回调。

  const throttledSetPosition = throttle(event => {
    if (event.touches[0].clientY) {
      if (slider.current.contains(event.target)) {
        setTouchPosition(Math.round(event.touches[0].clientY));
      }
    } else {
      setTouchPosition(null);
    }
  }, 200);

  const handleTouchMove = useCallback(throttledSetPosition, [touchPosition]);

第 2 部分 - Increasing/Decreasing 价值

要实现 increasing/decreasing 显示值的目标,您首先需要确定一个比例。您要显示的最大最小值是多少?让我们使用 100 因为这很容易理解。

然后你需要计算的是用户当前触摸的 100 的百分比,但相反(因为靠近顶部实际上更接近 100 而进一步向下更接近0).

为此,您可以使用以下内容:

// Define the scale
const scale = 100;

// Extract needed variables from event touches array
const {
  clientY,
  target: { offsetHeight, offsetTop }
} = event.touches[0];

// Calculate the percentage
const percentage = (clientY - offsetTop) / offsetHeight;

// Make the calculation to be reversed by subtracting the percentage from the scale...
const currentValue = scale - (percentage * scale);

// Set the display value
setTouchPosition(Math.round(currentValue));

我已经将你的 sandbox here 进行了上述修改。