本文主要是介绍React组件 - 实现侧滑删除,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
实现效果
组件源码
SlideContainer.js
import React, {useRef, useState} from "react";export const SlideContainer = (props) => {const childrenArray = React.Children.toArray(props.children);const [left, setLeft] = useState(0);const [leftOriginal, setleftOriginal] = useState(0);const [run, setRun] = useState(false);const touchX = useRef(null);const mouseDown = (event) => {const x = event.clientX;touchX.current = x;setRun(true);setleftOriginal(left)}const mouseMove = (event) => {if (!run) {return;}const x = event.clientX;const move = x - touchX.current;if (leftOriginal + move <= -1 * 50 * (window.innerWidth / 100)) { // 移出边界return;}if (leftOriginal + move >= 0) { // 移出边界return;}setLeft(leftOriginal + move);}const mouseUp = (event) => {if (!run) {return;}if (left < -1 * 25 * (window.innerWidth / 100)) {setLeft(-1 * 50 * (window.innerWidth / 100));} else {setLeft(0)}setRun(false);}return (<div style={{width: '100vw', height: '100px', position: 'relative', overflow: 'hidden'}}onMouseDown={mouseDown} onMouseMove={mouseMove} onMouseUp={mouseUp}><div style={{width: '150vw', position: 'absolute', display: 'flex', left: left + 'px'}}><div style={{width: '100vw'}}>{childrenArray[0]}</div><div style={{width: '50vw'}}>{childrenArray[1]}</div></div></div>)
}
使用样例
import {SlideContainer} from "./component/slide-view/slide-view";const App = ()=> {return (<SlideContainer><div>你好中国</div><div><button type='button' style={{width:'25vw'}}>预览</button><button type='button' style={{width:'25vw'}}>删除</button></div></SlideContainer>)
}
这篇关于React组件 - 实现侧滑删除的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!