指南 · 04
輸入與手勢
把指標、拖曳、捲動等輸入寫進值,並讓其他值追隨它們。
input(target, adapter)
輸入轉接器把瀏覽器事件轉成對值的寫入。input(ref, adapter) 把它當作控制器掛上;在 useAnimated 中宣告時,會在卸載或相依值改變時被移除。
轉接器:dragInput、pinchInput、moveInput、scrollInput、wheelInput、viewportInput、mediaInput、longPressInput 與 swipeInput。
正在準備範例…
有邊界的拖曳與放開後的動態
dragInput 支援指標與方向鍵拖曳、帶 elastic 阻力的 bounds、放開後的 momentum,以及依預測位置挑選停靠處的 settle 函式。
在觸控螢幕上,它會在掛載期間設定目標的 touch-action,避免瀏覽器把手勢當成捲動。你自己設定的值優先。
正在準備範例…
雙指縮放、可視範圍與媒體查詢
input 的第三個參數(選用)會收到每個回應事件,所以轉接器也能在邊緣上啟動動態。
const card = useRef(null);
const pinch = useAnimated(
{ scale: 1, rotation: 0 },
(value) => {
input(card, pinchInput({ scale: value.scale, rotation: value.rotation, minScale: 0.5 }));
},
[],
);
const reveal = useAnimated(
0,
(value) => {
input(card, viewportInput({ once: true }), (event) => {
if (event.phase === 'in') spring(value, { toValue: 1 }).start();
});
},
[],
);Animated.event
React Native 的事件對應可以用在 DOM 事件上。在捲動事件中,nativeEvent.contentOffset、contentSize 與 layoutMeasurement 會從被捲動的元素讀取,所以 ScrollView 的對應可以原封不動地移植。
const scrollY = useAnimatedValue(0);
<div onScroll={Animated.event([{ nativeEvent: { contentOffset: { y: scrollY } } }])} />;