在移动端隐藏箭头——小屏只用触摸滚动
在手机上打开它,或在 DevTools 里开启触摸模拟——箭头消失,滑动承担全部工作。
演示如何隐藏箭头
LeftArrow 与 RightArrow 都是可选属性——传入 undefined 时插槽根本不会渲染,因此无需用 CSS 隐藏,tab 顺序里也不会残留按钮。开关是副作用里的一个 matchMedia(’(pointer: coarse)’) 检查:服务端无法知道指针类型,所以首次绘制以桌面优先、带箭头,待确认指针为粗精度后 hydration 再移除它们。一个 change 监听器让它保持实时——DevTools 的设备模拟无需刷新即可翻转。
story 在触摸下做了什么
story 的 useSwipe hook 把自由平移变成翻页。柯里化的 onTouchStart、onTouchMove 与 onTouchEnd 属性各自接收 API 对象;start 重置结束坐标并记录 targetTouches[0].clientX,move 持续跟踪,end 测量移动的距离。超过 minSwipeDistance(20px)后就调用 apiObj.scrollPrev() 或 apiObj.scrollNext()——每次滑动平稳地翻一页,无论手指速度如何。
抑制原生触摸滚动
为了让翻页成为唯一的运动,浏览器自身的平移必须停下,而 React 18+ 以被动方式注册 touchmove 监听器,preventDefault 在那里会被忽略。story 的副作用通过 apiRef(ref.current.scrollContainer.current)拿到真实的滚动元素,并以 { passive: false } 附加自己的监听器,在那里这个调用才有效。
注意
- 要有意选择 SSR 默认值:先渲染箭头有利于爬虫与桌面用户,而触摸设备在 hydration 之后随即移除它们。
(pointer: coarse)针对的是输入方式而非屏幕尺寸——窄的桌面窗口保留箭头,平板则不会。- 如果你只想隐藏箭头并保留原生滑动(演示的行为),跳过 story 的
touchmove副作用即可——自由平移与隐藏的箭头可以良好共存。 - 触摸阈值是 20px,而桌面轻拂是 50px——鼠标变体见桌面端滑动示例。
完整源码
完整且可直接复制粘贴——这正是背后这份文件的 可在 Storybook 中实时编辑的版本.
import 'react-horizontal-scrolling-menu/dist/styles.css';
import styled from '@emotion/styled';
import React from 'react';
import {
type publicApiType,
ScrollMenu,
VisibilityContext,
} from 'react-horizontal-scrolling-menu';
export function MobileSwipeOnly() {
const [items] = React.useState(() => getItems());
const [selected, setSelected] = React.useState<string[]>([]);
const isItemSelected = (id: string): boolean =>
!!selected.find((el) => el === id);
const handleItemClick = (itemId: string) => {
const itemSelected = isItemSelected(itemId);
setSelected((currentSelected: string[]) =>
itemSelected
? currentSelected.filter((el) => el !== itemId)
: currentSelected.concat(itemId),
);
};
const { onTouchEnd, onTouchMove, onTouchStart } = useSwipe();
const ref = React.useRef<publicApiType>(null);
// React 18+ attaches touchmove listeners as passive, so preventDefault only
// works from a non-passive listener added manually to the scroll container.
React.useEffect(() => {
const onTouchMove = (ev: TouchEvent) => {
ev.preventDefault();
};
const node = ref.current?.scrollContainer.current;
node?.addEventListener('touchmove', onTouchMove, { passive: false });
return () => node?.removeEventListener('touchmove', onTouchMove);
}, [ref]);
return (
<NoScrollbar>
<ScrollMenu
LeftArrow={LeftArrow}
RightArrow={RightArrow}
onWheel={onWheel}
onTouchEnd={onTouchEnd}
onTouchMove={onTouchMove}
onTouchStart={onTouchStart}
apiRef={ref}
>
{items.map(({ id }) => (
<Card
title={id}
itemId={id} // NOTE: itemId is required for track items
key={id}
onClick={() => handleItemClick(id)}
selected={isItemSelected(id)}
/>
))}
</ScrollMenu>
</NoScrollbar>
);
}
export default MobileSwipeOnly;
export const useSwipe = () => {
const [touchStart, setTouchStart] = React.useState(0);
const [touchEnd, setTouchEnd] = React.useState(0);
// the required distance between touchStart and touchEnd to be detected as a swipe
const minSwipeDistance = 20;
const onTouchStart = () => (ev: React.TouchEvent) => {
setTouchEnd(0);
setTouchStart(ev.targetTouches[0].clientX);
};
const onTouchMove = () => (ev: React.TouchEvent) => {
setTouchEnd(ev.targetTouches[0].clientX);
};
const onTouchEnd = (apiObj: publicApiType) => () => {
if (!touchStart || !touchEnd) return false;
const distance = touchStart - touchEnd;
const isSwipe = Math.abs(distance) > minSwipeDistance;
const isLeftSwipe = distance < minSwipeDistance;
if (isSwipe) {
if (isLeftSwipe) {
apiObj.scrollPrev();
} else {
apiObj.scrollNext();
}
}
};
return { onTouchStart, onTouchEnd, onTouchMove };
};
const NoScrollbar = styled('div')({
'&': {
position: 'relative',
},
'& .react-horizontal-scrolling-menu--scroll-container::-webkit-scrollbar': {
display: 'none',
},
'& .react-horizontal-scrolling-menu--scroll-container': {
scrollbarWidth: 'none',
'-ms-overflow-style': 'none',
},
});
function LeftArrow() {
const visibility = React.useContext<publicApiType>(VisibilityContext);
const disabled = visibility.useLeftArrowVisible();
return (
<Arrow
disabled={disabled}
onClick={() => visibility.scrollPrev()}
testId="left-arrow"
>
Left
</Arrow>
);
}
function RightArrow() {
const visibility = React.useContext<publicApiType>(VisibilityContext);
const disabled = visibility.useRightArrowVisible();
return (
<Arrow
disabled={disabled}
onClick={() => visibility.scrollNext()}
testId="right-arrow"
>
Right
</Arrow>
);
}
function Arrow({
children,
disabled,
onClick,
className,
testId,
}: {
children: React.ReactNode;
disabled: boolean;
onClick: VoidFunction;
className?: string;
testId: string;
}) {
return (
<ArrowButton
disabled={disabled}
onClick={onClick}
className={'arrow' + `-${className}`}
data-testid={testId}
>
{children}
</ArrowButton>
);
}
const ArrowButton = styled('button')((props) => ({
cursor: 'pointer',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
marginBottom: '2px',
opacity: props.disabled ? '0' : '1',
userSelect: 'none',
borderRadius: '6px',
borderWidth: '1px',
}));
function Card({
onClick,
selected,
title,
itemId,
}: {
onClick: (context: publicApiType) => void;
selected: boolean;
title: string;
itemId: string;
}) {
const visibility = React.useContext<publicApiType>(VisibilityContext);
const isVisible = visibility.useIsVisible(itemId, true);
return (
<CardBody
data-cy={itemId}
onClick={() => onClick(visibility)}
onKeyDown={(ev: React.KeyboardEvent) => {
ev.code === 'Enter' && onClick(visibility);
}}
data-testid="card"
role="button"
tabIndex={0}
className="card"
visible={isVisible}
selected={selected}
>
<div className="header">
<div>{title}</div>
<div className="visible">visible: {JSON.stringify(isVisible)}</div>
<div className="selected">selected: {JSON.stringify(!!selected)}</div>
</div>
<div className="background" />
</CardBody>
);
}
const CardBody = styled('div')<{ selected?: boolean; visible?: boolean }>(
(props) => ({
border: '1px solid',
display: 'inline-block',
margin: '0 10px',
width: '160px',
userSelect: 'none',
borderRadius: '8px',
overflow: 'hidden',
'& .header': {
backgroundColor: 'white',
},
'& .visible': {
backgroundColor: props.visible ? 'transparent' : 'gray',
},
'& .background': {
backgroundColor: props.selected ? 'green' : 'bisque',
height: '200px',
},
}),
);
const getId = (index: number) => `${'test'}${index}`;
const getItems = () =>
Array(10)
.fill(0)
.map((_, ind) => ({ id: getId(ind) }));
function onWheel(apiObj: publicApiType, ev: React.WheelEvent): void {
// NOTE: no good standart way to distinguish touchpad scrolling gestures
// but can assume that gesture will affect X axis, mouse scroll only Y axis
// of if deltaY too small probably is it touchpad
const isThouchpad = Math.abs(ev.deltaX) !== 0 || Math.abs(ev.deltaY) < 15;
if (isThouchpad) {
ev.stopPropagation();
return;
}
if (ev.deltaY < 0) {
apiObj.scrollNext();
} else {
apiObj.scrollPrev();
}
}