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
,需要传参时写为箭头函数。