实现效果
组件源码
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>
)
}