Trong header
Ô tìm kiếm nằm giữa avatar và một nút.
Cách hoạt động
Phần tiêu đề “Cách hoạt động”containerStyle={{ flex: 1 }}cho ô chiếm phần chỗ còn lại.- Nút Cancel bị cắt trong phạm vi ô nên không đè lên nút bên cạnh.
- Có thể dùng y như vậy cho
headerTitlecủa React Navigation.
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 { Pressable, StyleSheet, Text, View } from 'react-native';import Search from 'react-native-search-box';
export default function Header() { const [count, setCount] = useState(2); const [query, setQuery] = useState(''); const reset = () => setQuery('');
return ( <View style={styles.screen}> {/* The box takes the room that the avatar and the button leave. */} <View style={styles.header}> <View style={styles.avatar}> <Text style={styles.avatarText}>AP</Text> </View> <Search backgroundColor="transparent" containerStyle={styles.box} inputHeight={34} inputBorderRadius={17} inputStyle={styles.input} searchIconExpandedMargin={14} placeholderExpandedMargin={28} cancelTitle="Done" onChangeText={setQuery} onDelete={reset} onCancel={reset} /> <Pressable accessibilityRole="button" accessibilityLabel={`Inbox, ${count} new`} onPress={() => setCount(0)} style={styles.button} > <Text style={styles.buttonText}>✉</Text> {count > 0 && <Text style={styles.badge}>{count}</Text>} </Pressable> </View> <View style={styles.content}> <Text style={styles.title}>{query ? `Searching “${query}”` : 'Your feed'}</Text> {[1, 2, 3].map((card) => ( <View key={card} style={styles.card} /> ))} </View> </View> );}
const styles = StyleSheet.create({ screen: { flex: 1, backgroundColor: '#f0fdfa' }, header: { flexDirection: 'row', alignItems: 'center', gap: 6, paddingHorizontal: 12, height: 56, backgroundColor: '#0f766e', }, avatar: { width: 34, height: 34, borderRadius: 17, backgroundColor: '#5eead4', alignItems: 'center', justifyContent: 'center', }, avatarText: { fontSize: 12, fontWeight: '700', color: '#134e4a' }, box: { flex: 1 }, input: { fontSize: 15, color: '#134e4a' }, button: { width: 34, height: 34, alignItems: 'center', justifyContent: 'center' }, buttonText: { fontSize: 22, color: '#fff' }, badge: { position: 'absolute', top: -2, right: -2, minWidth: 16, textAlign: 'center', fontSize: 11, color: '#fff', backgroundColor: '#dc2626', borderRadius: 8, overflow: 'hidden', }, content: { padding: 16, gap: 12 }, title: { fontSize: 22, fontWeight: '700', color: '#134e4a' }, card: { height: 120, borderRadius: 16, backgroundColor: '#ccfbf1' },});