(编辑:jimmy 日期: 2025/11/13 浏览:2)
最近做了一个类似系统操作的左滑删除的demo,用的taro框架,和大家分享一下~
首先需要考虑的有以下几点:
1)布局;
2)判断是左滑还是右滑,左滑时出现删除,右滑时回归原位;
3)排他性,意思是某一个时间只能有一个项出现删除,当有另一个出现删除时,上一个自动回归原位。
我将列表项封装成一个组件,而整个列表是另一个组件。
接下来先说列表项这个组件,逐一解决以上这些问题:
1)布局
我采用的是列表项最外层套一个盒子,这个盒子宽度设置为100vw,并且overflow:hidden。而列表项要包括内容和删除按钮,内容宽度为屏幕宽度,而删除按钮定位到右边,所以整个列表项宽度是超过100vw的。描述可能没有那么清晰,直接上代码:
<View className='swipe-item'>
<View className='swipe-item-wrap' style={moveStyle}>
<View
className='swipe-item-left'
onTouchStart={this.handleTouchStart}
onTouchMove={this.handleTouchMove.bind(this, index)}
onTouchEnd={this.handleTouchEnd}
>
<View>{item.title}</View>
</View>
<View className='swipe-item-right'>
<View className='swipe-item-del'>del</View>
</View>
</View>
</View>
.swipe-item {
width: 100vw;
overflow: hidden;
line-height: 24PX;
height: 24PX;
text-align: center;
margin-bottom: 10PX;
&-wrap {
width: calc(100vw + 32PX);
height: 100%;
position: relative;
}
&-left {
width: 100vw;
}
&-right {
width: 32PX;
height: 100%;
background: pink;
position: absolute;
right: 0;
top: 0;
}
}
好了,布局结束之后,接下来是第二个问题:
2)判断是左滑还是右滑,左滑时出现删除,右滑时回归原位
可以看到上面的代码,我已经在列表项左边部分加了touch的一系列事件,下面就来分析下这几个事件
上代码了~
handleTouchStart = e => {
this.startX = e.touches[0].pageX
this.startY = e.touches[0].pageY
}
handleTouchMove (index, e) {
// 若想阻止冒泡且最外层盒子为scrollView,不可用e.stopPropogagation(),否则页面卡死
this.currentX = e.touches[0].pageX
this.moveX = this.currentX - this.startX
this.moveY = e.touches[0].pageY - this.startY
// 纵向移动时return
if (Math.abs(this.moveY) > Math.abs(this.moveX)) {
return
}
// 滑动超过一定距离时,才触发
if (Math.abs(this.moveX) < 10 ) {
return
}
else {
// 否则没有动画效果
this.setState({
hasTransition: true
})
}
// 通知父组件当前滑动的为第几项
this.props.onSetCurIndex(index)
}
handleTouchEnd = e => {
// 结束时,置为true,否则render时不生效
this.setState({
hasTransition: true
})
}
3)排他性
这个主要是通过触发父组件的一个事件,在父组件中设置一个当前滑动项的index值,然后再通过props值传入子组件,渲染的时候加一个判断实现。
// 左滑时,出现del,右滑时,恢复原位,距离为操作按钮大小 // 也可以将滑动距离作为移动距离,但是效果不太好 const distance = this.moveX >= 0 "htmlcode">handleCurIndex = index => { // 设置当前滑动项,做排他性 this.setState({ currentIndex: index }) } <SwipeItem item={item} key={item.id} index={index} currentIndex={currentIndex} onSetCurIndex={this.handleCurIndex} />好了,大致就是这些了,可能有点混乱,大家可以移步demo源码~
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。