您好,登錄后才能下訂單哦!
在React Native中,可以使用react-navigation
庫來實現導航欄搜索框。以下是一個簡單的示例:
react-navigation
庫及其相關依賴。如果尚未安裝,可以使用以下命令進行安裝:npm install @react-navigation/native @react-navigation/stack
SearchBar.js
組件,用于實現搜索框:import React, { useState } from 'react';
import { View, TextInput, StyleSheet } from 'react-native';
const SearchBar = ({ onSearch }) => {
const [searchTerm, setSearchTerm] = useState('');
const handleSearch = () => {
onSearch(searchTerm);
};
return (
<View style={styles.searchContainer}>
<TextInput
style={styles.searchInput}
placeholder="搜索"
value={searchTerm}
onChangeText={setSearchTerm}
/>
<Button title="搜索" onPress={handleSearch} />
</View>
);
};
const styles = StyleSheet.create({
searchContainer: {
flexDirection: 'row',
alignItems: 'center',
backgroundColor: '#f5f5f5',
paddingHorizontal: 10,
},
searchInput: {
flex: 1,
height: 40,
borderColor: 'gray',
borderWidth: 1,
marginRight: 10,
borderRadius: 4,
},
});
export default SearchBar;
App.js
)中,設置導航欄并使用SearchBar
組件:import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import SearchBar from './SearchBar';
const Stack = createStackNavigator();
const HomeScreen = ({ navigation }) => {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<SearchBar onSearch={(searchTerm) => navigation.navigate('Results', { searchTerm })} />
</View>
);
};
const ResultsScreen = ({ route }) => {
const { searchTerm } = route.params;
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>搜索結果:{searchTerm}</Text>
</View>
);
};
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="首頁" component={HomeScreen} />
<Stack.Screen name="結果" component={ResultsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
};
export default App;
現在,當用戶在搜索框中輸入文本并點擊搜索按鈕時,應用程序將導航到ResultsScreen
,并顯示搜索結果。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。