【react】react实现长按弹出删除按钮

效果图如下:
长按之前:
在这里插入图片描述
长按之后:
在这里插入图片描述
若不想删除,在除删除按钮以外的地方单击即可。

下面是在react中的实现

//ThanksStyle.Item是要添加长按事件的对象
<ThanksStyle.Item  key={index}  onTouchStart={() => this.onItemTouchStart(index)}   onTouchEnd={this.onItemTouchEnd} >
                    <ThanksStyle.Left>
                      <ThanksStyle.Title>{value.nickname}</ThanksStyle.Title>
                      <ThanksStyle.Time>{value.time}</ThanksStyle.Time>
                    </ThanksStyle.Left>
                    <ThanksStyle.Right>
                      <ThanksStyle.Love bg={love} />
                      <ThanksStyle.Num>{value.num}</ThanksStyle.Num>
                      {
                        // 删除按钮
                        <ThanksStyle.DeleteBtn
                          className={cn({ show: this.state.currentDeleteIndex === index })}
                        >
                          删除
                        </ThanksStyle.DeleteBtn>
                      }
                    </ThanksStyle.Right>
</ThanksStyle.Item>

其中onItemTouchStart(currentItem)和onItemTouchEnd函数的实现如下:

  longPressInterval = 600;     //longPressInterval长按的毫秒数
  longPressItemTimeOut;      //setTimeOut的返回值    为了清掉定时器
  constructor(props) {
    super(props);
    this.state = {
      currentDeleteIndex: -1      //currentDeleteIndex要出现删除按钮的当前Item的index,默认为-1
    };
  }
  onItemTouchStart = currentItem => {
 
    this.startTime = +new Date();
    this.longPressItemTimeOut = setTimeout(
      () => this.onLongPressItem(currentItem),
      this.longPressInterval
    );
  };
  onLongPressItem(currentItem) {
    this.setState({
      currentDeleteIndex: currentItem
    });
  }
  onItemTouchEnd = () => {
    this.endTime = +new Date();
    const interval = this.endTime - this.startTime;   //长按时长
    
    if (interval < this.longPressInterval) {      //按键时长<600,默认是点击事件
      // TODO click操作  点击进入对应的Item
      clearTimeout(this.longPressItemTimeOut);
      this.setState({
        currentDeleteIndex: -1
      });
    } else {        //按键时长>600   长按
      // TODO 长按操作
    }
  };

删除按钮对应的样式如下:

export const DeleteBtn = styled.div`
  position: relative;
  top: -0.57rem;
  margin-left: 0.38rem;
  width: 0.7rem;
  height: 0.62rem;
  line-height: 0.62rem;
  font-size: 0.16rem;
  background: #e94a14;
  text-align: center;
  color: #fff;
  display: none;
  &.show {
    display: block;
  }
`;

这样就可以实现长按操作啦~

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值