小编典典

在React JS中滑动效果

reactjs

我正在尝试使用React创建滑动事件。我不想使用任何外部组件或jquery。

CSS是这样的:

.outter{
  position:relative;
  width: 100%;
  height: 150px;
  background-color: blue;
}

.inner{
  position: absolute;
  width: 1000%; 
  left: 50px;
}
.child{
  float: left;
  margin-right: 15px;
}

在react组件中,我正在尝试执行以下操作:

class Test extends React.Component {
    constructor(props){
    super(props);

    this.state = {
        left: 0
    }
  }

  handleSwipe(){
    this.setState({left: -350})
  }

  render(){
    return(
        <div className="outter">
            <div className="inner" style={{left: this.state.left}} onSwipe={this.handleSwipe.bind(this)}>
                 <div className="child"><img src="http://placehold.it/350x150" /></div>
                 <div className="child"><img src="http://placehold.it/350x150" /></div>
                 <div className="child"><img src="http://placehold.it/350x150" /></div>
                 <div className="child"><img src="http://placehold.it/350x150" /></div>
            </div>
      </div>
    )
  }
}

React.render(<Test />, document.getElementById('container'));

如何识别滑动事件?

如果在我的示例中而不是onSwipe添加onClick它,它可以工作,但是如何制作滑动效果?

这是jsfiddle


阅读 813

收藏
2020-07-22

共1个答案

小编典典

您可以将onTouch事件处理程序添加到您的React组件中:

onTouchStart={touchStartEvent => this.handleTouchStart(touchStartEvent)}
onTouchMove={touchMoveEvent => this.handleTouchMove(touchMoveEvent)}
onTouchEnd={() => this.handleTouchEnd()}

您可能还想为鼠标事件添加事件处理程序,以实现跨平台兼容性:

onMouseDown={mouseDownEvent => this.handleMouseDown(mouseDownEvent)}
onMouseMove={mouseMoveEvent => this.handleMouseMove(mouseMoveEvent)}
onMouseUp={() => this.handleMouseUp()}
onMouseLeave={() => this.handleMouseLeave()}

您有正确的想法来更新left事件处理程序中的state属性,但是如果您希望滑动功能感觉自然,则需要通过left使用来更新指针来跟踪指针的位置(无论是鼠标还是触摸)事件的clientX属性。

为此,您需要存储第一次触摸的位置,并将其设置为left等于触摸位置的变化。为了增加真实感,您还可以跟踪触摸的速度,并在触摸完成后继续为组件设置动画。

这是我制作的快速n肮脏的Codepen,用于从列表中删除项目:

https://codepen.io/swingthing/pen/ZBGBJb/

2020-07-22