• React组件 - 实现侧滑删除


    实现效果

    组件源码

    SlideContainer.js
    1. import React, {useRef, useState} from "react";
    2. export const SlideContainer = (props) => {
    3. const childrenArray = React.Children.toArray(props.children);
    4. const [left, setLeft] = useState(0);
    5. const [leftOriginal, setleftOriginal] = useState(0);
    6. const [run, setRun] = useState(false);
    7. const touchX = useRef(null);
    8. const mouseDown = (event) => {
    9. const x = event.clientX;
    10. touchX.current = x;
    11. setRun(true);
    12. setleftOriginal(left)
    13. }
    14. const mouseMove = (event) => {
    15. if (!run) {
    16. return;
    17. }
    18. const x = event.clientX;
    19. const move = x - touchX.current;
    20. if (leftOriginal + move <= -1 * 50 * (window.innerWidth / 100)) { // 移出边界
    21. return;
    22. }
    23. if (leftOriginal + move >= 0) { // 移出边界
    24. return;
    25. }
    26. setLeft(leftOriginal + move);
    27. }
    28. const mouseUp = (event) => {
    29. if (!run) {
    30. return;
    31. }
    32. if (left < -1 * 25 * (window.innerWidth / 100)) {
    33. setLeft(-1 * 50 * (window.innerWidth / 100));
    34. } else {
    35. setLeft(0)
    36. }
    37. setRun(false);
    38. }
    39. return (
    40. <div style={{width: '100vw', height: '100px', position: 'relative', overflow: 'hidden'}}
    41. onMouseDown={mouseDown} onMouseMove={mouseMove} onMouseUp={mouseUp}
    42. >
    43. <div style={{width: '150vw', position: 'absolute', display: 'flex', left: left + 'px'}}>
    44. <div style={{width: '100vw'}}>{childrenArray[0]}div>
    45. <div style={{width: '50vw'}}>{childrenArray[1]}div>
    46. div>
    47. div>
    48. )
    49. }
    使用样例
    1. import {SlideContainer} from "./component/slide-view/slide-view";
    2. const App = ()=> {
    3. return (
    4. <SlideContainer>
    5. <div>你好中国div>
    6. <div>
    7. <button type='button' style={{width:'25vw'}}>预览button>
    8. <button type='button' style={{width:'25vw'}}>删除button>
    9. div>
    10. SlideContainer>
    11. )
    12. }

  • 相关阅读:
    05_模板引擎
    解决hadoop使用put上传报错问题
    框架内容整理
    零担物流市场数据,市场热点,政策规划,竞争情报分析
    ElasticSearch之路
    R语言的入门学习
    vulnhub之Nagini
    专项学习:软件开发
    java多线程为什么每个线程都有一个单独的栈 ?
    SpringBoot整合百度云人脸识别功能
  • 原文地址:https://blog.csdn.net/qq_37011724/article/details/136664426