React-Native 创建笑话生成器应用程序
在本文中,我们将使用React Native构建一个笑话生成器应用程序。React Native使您能够在无意中从外部API中轻松检索笑话的同时,掌握设计优雅和动态用户界面。
让我们来看看我们完成的项目将会是什么样子
先决条件/使用的技术
- React Native介绍
- React Native组件
- React Hooks
- Node.js和npm
方法
“随机笑话生成器”应用程序无缝从外部API(https://icanhazdadjoke.com/)检索笑话,连续提供幽默. 它用户友好的界面采用了结构良好的布局,包括标题、笑话容器和易于访问的“获取笑话”按钮,实现了平滑互动. 该应用通过在充满优雅的白色容器中呈现笑话,并带有圆角和阴影,增强了视觉体验. 点击按钮,用户可以轻松享受新鲜笑话并保持参与.
创建React Native应用程序的步骤
步骤1: 创建一个React Native应用程序
为JokesGeneratorApp创建一个新的React Native项目
npx react-native init JokesGeneratorApp
步骤2: 更改目录到项目文件夹:
cd JokesGeneratorApp
项目结构
依赖关系 //package.json
{
"dependencies": {
"react-native-paper": "4.9.2",
"@expo/vector-icons": "^13.0.0"
}
}
示例: 在这个示例中,我们将使用上面解释的方法
// App.js file
import React, { useState } from "react";
import {
View,
Text,
StyleSheet,
TouchableOpacity,
StatusBar,
} from "react-native";
const App = () => {
const [joke, setJoke] = useState("");
const getJoke = async () => {
try {
const response = await fetch(
"https://icanhazdadjoke.com/",
{
headers: {
Accept: "application/json",
},
}
);
const data = await response.json();
setJoke(data.joke);
} catch (error) {
console.error(error);
}
};
return (
<View style={styles.container}>
<StatusBar
backgroundColor="#252627"
barStyle="light-content"/>
<Text style={styles.title}>
Random Jokes Generator
</Text>
<View style={styles.jokeContainer}>
<Text style={styles.jokeText}>{joke}</Text>
</View>
<TouchableOpacity
style={styles.button}
onPress={getJoke}>
<Text style={styles.buttonText}>
Get a Joke
</Text>
</TouchableOpacity>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#eee",
alignItems: "center",
justifyContent: "center",
padding: 16,
},
title: {
fontSize: 28,
fontWeight: "bold",
color: "#333739",
marginBottom: 24,
textAlign: "center",
},
jokeContainer: {
backgroundColor: "white",
borderRadius: 15,
padding: 20,
marginBottom: 24,
width: "100%",
alignItems: "center",
shadowColor: "black",
shadowOffset: { width: 1, height: 2 },
shadowRadius: 15,
shadowOpacity: 1,
elevation: 4,
},
jokeText: {
fontSize: 22,
fontWeight: "300",
lineHeight: 30,
color: "#333739",
textAlign: "center",
},
button: {
padding: 16,
backgroundColor: "green",
borderRadius: 10,
shadowColor: "black",
shadowOffset: { width: 1, height: 2 },
shadowRadius: 15,
shadowOpacity: 1,
elevation: 4,
},
buttonText: {
fontSize: 20,
color: "white",
fontWeight: "bold",
},
});
export default App;
运行步骤
要运行React Native应用程序,请使用以下命令:
npx expo start
- 在Android上运行:
npx react-native run-android
- 在iOS上运行:
npx react-native run-ios
输出: