我有一个div,当我向上拖动手指时,我希望div内的数字增加。
当我向下拖动手指时,我希望内部的数字减少。
这很容易通过触摸事件实现。
codesandbox在这里-我试图使其尽可能简单! Codesandbox
我有问题的地方是,事件真的很快触发了,因此很难降落到特定的数字上。使用lodash节流功能来节流该事件会很棒,但是在这里我遇到了问题!什么也没发生!
我尝试像这样使用useRef:
const throttledPosition = useRef(throttle(touchPosition => touchPosition, 200)).current;
再次,什么也没有发生。
[我认为您的问题可能是您使用_.throttle()
的方式,它实际上应该包裹在事件处理程序中。
我已将您的sandbox here分叉给您。
这里是touchSlider.jsx
现在的样子:
export default function TouchSlider() {
const slider = useRef();
const [touchPosition, setTouchPosition] = useState(null);
const handleTouchMove = useCallback(
throttle(event => {
if (event.touches[0].clientY) {
if (slider.current.contains(event.target)) {
setTouchPosition(Math.round(event.touches[0].clientY));
}
} else {
setTouchPosition(null);
}
}, 200),
[touchPosition]
);
useEffect(() => {
window.addEventListener("touchmove", handleTouchMove);
return () => {
window.removeEventListener("touchmove", handleTouchMove);
};
}, [handleTouchMove]);
return (
<div className="touchSlider">
<div className="sliderBox" ref={slider}>
{touchPosition}
</div>
</div>
);
}
关键的变化是用throttle
包装事件回调。
const handleTouchMove = useCallback(
throttle(event => {
if (event.touches[0].clientY) {
if (slider.current.contains(event.target)) {
setTouchPosition(Math.round(event.touches[0].clientY));
}
} else {
setTouchPosition(null);
}
}, 200),
[touchPosition]
);
请参见lodash.throttle() docs
中的示例以供参考。