溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

React Native的導(dǎo)航欄搜索框?qū)崿F(xiàn)

發(fā)布時(shí)間:2024-10-02 14:26:49 來(lái)源:億速云 閱讀:81 作者:小樊 欄目:web開(kāi)發(fā)

在React Native中,可以使用react-navigation庫(kù)來(lái)實(shí)現(xiàn)導(dǎo)航欄搜索框。以下是一個(gè)簡(jiǎn)單的示例:

  1. 首先,確保已經(jīng)安裝了react-navigation庫(kù)及其相關(guān)依賴。如果尚未安裝,可以使用以下命令進(jìn)行安裝:
npm install @react-navigation/native @react-navigation/stack
  1. 創(chuàng)建一個(gè)SearchBar.js組件,用于實(shí)現(xiàn)搜索框:
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;
  1. 在主組件(例如App.js)中,設(shè)置導(dǎo)航欄并使用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>搜索結(jié)果:{searchTerm}</Text>
    </View>
  );
};

const App = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="首頁(yè)" component={HomeScreen} />
        <Stack.Screen name="結(jié)果" component={ResultsScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
};

export default App;

現(xiàn)在,當(dāng)用戶在搜索框中輸入文本并點(diǎn)擊搜索按鈕時(shí),應(yīng)用程序?qū)?dǎo)航到ResultsScreen,并顯示搜索結(jié)果。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI