react 滑动删除组件

import React from "react";

import "./style.less";

class SlideItem extends React.Component {
    constructor(props) {
        super(props);
        this.state = {};
    }

    componentDidMount() {}

    handleTouchStart = e => {
        this.startX = e.touches[0].pageX;
        this.startY = e.touches[0].pageY;
    }
         
    handleTouchMove = 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;
        }
        const distance = this.moveX >= 0 ? 0 : -70;
        this.setState({
            moveStyle: {
                transform:`translateX(${distance}px)`
            }
        });
    }
         
    render() {
        let { moveStyle } = this.state;

        return (
            <React.Fragment>
                <div className="slide-item-wrap">
                    <div className="slide-item-children"
                        style={moveStyle}
                        onTouchStart={this.handleTouchStart}
                        onTouchMove={this.handleTouchMove}
                    >
                        {
                            this.props.children
                        }
                    </div>
                    <div
                        className="delete-btn"
                        onClick={() => this.props.onDelete()}
                    >
                        删除
                    </div>
                </div>
            </React.Fragment>
        );
    }
}

export default SlideItem;

  样式:

.slide-item-wrap {
    width: 345px;
    height: 86px;
    background: #FFFFFF;
    border-radius: 5px;
    position: relative;
    overflow: hidden;
    margin-bottom: 12px;

    .slide-item-children {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 2;
        transition: transform 0.3s ease;
    }

    .delete-btn {
        position: absolute;
        top: 0;
        right: 0;
        width: 70px;
        height: 100%;
        background: #FC5A45;
        z-index: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 13px;
        color: #FFFFFF;
        border-radius: 0 5px 5px 0;
    }
}

  https://segmentfault.com/a/1190000019654209?utm_source=tag-newest

posted @ 2021-04-22 15:59  Peter_Yang0942  阅读(418)  评论(0编辑  收藏  举报