NetworkError公共組件
import SimpleLineIcons from "@expo/vector-icons/SimpleLineIcons";
import { StyleSheet, Text, View } from "react-native";export default function NetworkError() {return (<View style={styles.container}><SimpleLineIcons name={"drawer"} size={160} color={"#ddd"} /><Text style={styles.title}>抱歉,網絡連接出錯了!</Text></View>);
}const styles = StyleSheet.create({container: {flex: 1,backgroundColor: "#fff",alignItems: "center",justifyContent: "center",},title: {color: "#999",},
});
import { useEffect, useState } from "react";
import { StyleSheet, Text, View } from "react-native";
import NetworkError from "./components/shared/NetworkError";export default function App() {const [courses, setCourses] = useState([]);const [keyword, setKeyword] = useState("");const [error, setError] = useState(false);/*** 獲取搜索接口課程數據* @returns { Promise<void> }*/const fetchData = async () => {try {const res = await fetch(`http://192.168.1.138/search?q=${keyword}`);const { data } = await res.json();setCourses(data.courses);console.log("獲取到的數據是:", data.courses);} catch (error) {console.error("獲取數據失敗:", error);setError(true);}};useEffect(() => {fetchData();}, []);return (<View style={styles.container}>{error ? (<NetworkError />) : (<>{courses.map((course) => (<Text key={course.id}>{course.name}</Text>))}</>)}</View>);
}const styles = StyleSheet.create({container: {flex: 1,backgroundColor: "#fff",alignItems: "center",justifyContent: "center",},input: {height: 40,width: 300,margin: 12,padding: 10,borderWidth: 1,borderColor: "#ccc",borderRadius: 5,},
});
然后我們把后端服務停掉,然后接口請求肯定會報錯,直接進入我們的自定義錯誤處理:
這里使用到的圖標,都是 rn 內置的,無需安裝,以下是使用方法和所有的圖標:
https://docs.expo.dev/guides/icons/
https://oblador.github.io/react-native-vector-icons/
TouchableOpacity 組件
Button
組件在iOS
與Android
上的UI
是不一致的。可以改用TouchableOpacity組件來開發。
這是一個點擊后可以改變透明度的組件,與它類似的還有組件:
- TouchableHighlight:點擊后高亮
- TouchableWithoutFeedback:點擊后無反饋
這三個組件,使用方式都是一樣的,只是在點擊后,顯示的有點小區別而已。
打開NetworkError.js
,來引用一下:
import { TouchableOpacity } from 'react-native';
然后到提示信息下面,使用它:
<TouchableOpacity style={styles.reload} onPress={onReload}><Text style={styles.label}>重新加載</Text>
</TouchableOpacity>
- 用起來非常簡單,直接用它,包住
Text
組件就行了。
打開App
,按鈕的樣子已經出來了。這個按鈕,點擊它,按住不放的時候,它會有個透明度的改變。
這里有一個需要注意點,onPress={onReload} onReload 要么直接寫,要么寫成箭頭函數的形式 () => onReload()
。因為如果寫成 onReload()
是函數的直接調用,不論是否點擊,都會直接執行。所以,簡寫為 onReload
,需要傳參時寫為箭頭函數。