在React中检测向左/向右滑动

时间:2019-06-19 05:01:18

标签: javascript reactjs

我正在尝试检测左右滑动,但是我遇到了一个问题,例如,如果用户向上或向下滑动并稍微向一侧滑动,则会将其检测为向左滑动(例如)

constructor(props) {
    super(props)

    this.state = {
        initialClientX: 0,
        finalClientX: 0,
    }
}

handleTouchStart(event) {
    this.setState({
        initialClientX: event.nativeEvent.touches[0].clientX
    });
}

handleTouchMove(event) {
    this.setState({
        finalClientX: event.nativeEvent.touches[0].clientX
    });
}

handleTouchEnd() {
    if (this.state.finalClientX < this.state.initialClientX) {
        console.log('swipe left')
    }

    this.setState({
        initialClientX: 0,
        finalClientX: 0
    });
}

如何使它不太敏感?我还应该跟踪clientY吗?

1 个答案:

答案 0 :(得分:0)

我最终还检查了 clientY 和阈值

if ((this.state.finalClientX > this.state.initialClientX)
    && (this.state.finalClientY - this.state.initialClientY < 10)) {
        console.log('swipe left')
}