Ẩn khi cuộn
Thanh tìm kiếm ẩn khi cuộn xuống và hiện lại khi cuộn lên.
Cách hoạt động
Phần tiêu đề “Cách hoạt động”Animated.diffClampbám theo quãng cuộn trong khoảng từ 0 đến chiều cao thanh.- Thanh di chuyển bằng
translateYtrên native driver. Danh sách có padding trên bằng chiều cao đó. - Bản thân ô tìm kiếm không cần cấu hình gì thêm.
Dùng
Toàn bộ source
Phần tiêu đề “Toàn bộ source”Đây chính là đoạn code đang chạy trong điện thoại. Chép vào app của bạn là dùng được.
import { useState } from 'react';import { Animated, Platform, StyleSheet, Text, View } from 'react-native';import Search from 'react-native-search-box';
const BAR_HEIGHT = 56;const GROUPS = ['Design team', 'Family', 'Book club', 'Landlord', 'Running group'];const CHATS = Array.from({ length: 40 }, (_, i) => ({ id: String(i), name: `${GROUPS[i % 5]} ${i + 1}` }));
function createBar() { const scrollY = new Animated.Value(0); // Overscroll (below 0) must not count as scrolling up. const distance = scrollY.interpolate({ inputRange: [0, 1], outputRange: [0, 1], extrapolateLeft: 'clamp', }); return { onScroll: Animated.event([{ nativeEvent: { contentOffset: { y: scrollY } } }], { useNativeDriver: Platform.OS !== 'web', }), translateY: Animated.multiply(Animated.diffClamp(distance, 0, BAR_HEIGHT), -1), };}
export default function HideOnScroll() { const [query, setQuery] = useState(''); const [bar] = useState(createBar); const reset = () => setQuery('');
return ( <View style={styles.screen}> <Animated.FlatList data={CHATS.filter((chat) => chat.name.toLowerCase().includes(query.toLowerCase()))} keyExtractor={(chat) => chat.id} contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled" onScroll={bar.onScroll} scrollEventThrottle={16} renderItem={({ item }) => ( <View style={styles.row}> <View style={styles.avatar} /> <View> <Text style={styles.name}>{item.name}</Text> <Text style={styles.message}>See you there</Text> </View> </View> )} /> <Animated.View style={[styles.bar, { transform: [{ translateY: bar.translateY }] }]}> <Search backgroundColor="#fff" titleCancelColor="#2563eb" inputHeight={BAR_HEIGHT - 18} inputBorderRadius={19} inputStyle={styles.input} containerStyle={styles.box} searchIconExpandedMargin={18} placeholderExpandedMargin={34} onChangeText={setQuery} onDelete={reset} onCancel={reset} /> </Animated.View> </View> );}
const styles = StyleSheet.create({ screen: { flex: 1, backgroundColor: '#fff', overflow: 'hidden' }, bar: { position: 'absolute', top: 0, left: 0, right: 0, height: BAR_HEIGHT, backgroundColor: '#fff' }, box: { marginTop: 4 }, input: { fontSize: 16, backgroundColor: '#f1f5f9', color: '#111' }, content: { paddingTop: BAR_HEIGHT }, row: { flexDirection: 'row', alignItems: 'center', gap: 12, paddingHorizontal: 16, paddingVertical: 10 }, avatar: { width: 48, height: 48, borderRadius: 24, backgroundColor: '#dbeafe' }, name: { fontSize: 16, fontWeight: '600', color: '#111' }, message: { color: '#6b7280', marginTop: 2 },});