发布实战

React Native 教程 · 第 8 章 · 8 次浏览

RN 打包发布和原生类似:Android 出 APK,iOS 出 ipa。Expo 项目还能用 EAS Build 云打包,免配原生环境。

发布方式

  • Expo 项目:eas build -p android 云打包,简单
  • RN CLI 项目:Android Studio 打开 android 目录,Build Signed APK
  • iOS:Xcode 打开 ios 目录,Archive 上传

实战:天气查询 App

输入城市 → 请求天气 API → 展示温度天气。串起状态、请求、UI 全流程。

代码示例

import { useState } from "react";
import { View, Text, TextInput, Button, StyleSheet } from "react-native";

const App = () => {
  const [city, setCity] = useState("");
  const [weather, setWeather] = useState(null);

  const fetchWeather = async () => {
    try {
      const res = await fetch(
        `https://api.example.com/weather?city=${encodeURIComponent(city)}`
      );
      const data = await res.json();
      setWeather(data);
    } catch (e) {
      alert("查询失败,请检查城市名或网络");
    }
  };

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        placeholder="输入城市,如 烟台"
        value={city}
        onChangeText={setCity}
      />
      <Button title="查询天气" onPress={fetchWeather} />
      {weather && (
        <View style={styles.result}>
          <Text style={styles.city}>{weather.city}</Text>
          <Text style={styles.temp}>{weather.temp}°C</Text>
          <Text>{weather.desc}</Text>
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20, paddingTop: 60 },
  input: { borderWidth: 1, borderColor: "#ddd", padding: 10, borderRadius: 6, marginBottom: 12 },
  result: { marginTop: 20, alignItems: "center" },
  city: { fontSize: 22, fontWeight: "bold" },
  temp: { fontSize: 48, color: "#33691E", marginVertical: 8 }
});

export default App;
📚 JavaScript 语法速查
常用条目速查,完整版见对应教程章节。可复制代码到在线运行中测试。
写法 / 语法作用
let x = 1;声明变量(可重新赋值)
const y = 2;声明常量(不可重新赋值)
var 已过时旧式变量声明,建议用 let/const
if (条件) { } else { }条件判断
for (let i = 0; i < n; i++) { }循环
while (条件) { }条件循环
function fn(a, b) { return a + b; }函数声明
const fn = (a) => a + 1;箭头函数
array.push(x) / pop()数组尾部添加 / 删除
array.map(fn) / filter(fn)数组映射 / 过滤
obj.key / obj["key"]访问对象属性
JSON.stringify(obj)对象转 JSON 字符串
JSON.parse(str)JSON 字符串转对象
document.getElementById("id")按 id 取元素
document.querySelector("选择器")按选择器取第一个元素
element.textContent读写元素文本
element.innerHTML读写元素 HTML(慎用,防 XSS)
element.addEventListener("click", fn)绑定事件
console.log(x)控制台输出(调试)
setTimeout(fn, 1000)延迟执行(毫秒)
window.location.href当前页面地址(可赋值跳转)
localStorage.setItem("k", v)本地存储写入
localStorage.getItem("k")本地存储读取
new Promise((resolve, reject) => {})Promise 异步处理
async / await异步函数语法糖