0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

初心者がExpo + React Nativeでとりあえず1画面動かしてみた話

Posted at

はじめに

React NativeとExpoを使って、モバイルアプリを作り始めてみました。
とりあえず「1機能」程度のものでも自分のスマホ上で動けばモチベーションが上がるはず!
ということで、環境構築から簡単な画面表示までをサクッとまとめます。

環境

  • Expo (Managed Workflow)
  • React Native
  • VSCode (Windows環境でWSL2を使用)
    特にカスタム構成はしていません。npx create-expo-appでプロジェクトを作り、そのまま開発を始めました。

やったこと

  • プロジェクトを作成
npx create-expo-app my-app
cd my-app
npm install
  • 開発サーバー起動
npx expo start

ブラウザに「QRコード」が表示されます。
スマホにExpo Goアプリを入れてQRコードを読み込むと、スマホ上でアプリが立ち上がりました!

  • 1機能分の画面追加
    appディレクトリ内に新しい画面コンポーネントをindex.tsxとして配置し、簡単なテキストとボタンを並べてみます。
// app/index.tsx
import { View, Text, Button, StyleSheet } from 'react-native';
import { useRouter } from 'expo-router';

export default function IndexScreen() {
  const router = useRouter();

  return (
    <View style={styles.container}>
      <Text style={styles.text}>Hello World!</Text>
      <Button title="次の画面へ" onPress={() => router.push('/next')} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
  },
  text: {
    fontSize: 20,
    marginBottom: 20
  }
});

このように書くと、アプリ起動時に「Hello World!」と「次の画面へ」ボタンが表示されるようになりました。

  • 別の画面を用意して遷移
    app/next.tsxを追加して、ボタンタップ時に遷移できるようにします。
// app/next.tsx
import { View, Text, StyleSheet } from 'react-native';

export default function NextScreen() {
  return (
    <View style={styles.container}>
      <Text style={styles.text}>これは次の画面です。</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff'
  },
  text: {
    fontSize: 20
  }
});

これで「次の画面へ」ボタンを押すと/next画面へ移動することができます。
Expo Routerを使うことで、ディレクトリ構成に従った自動的なルーティングができて便利でした。

ハマったポイント

ホットリロードが効かない時がありましたが、npx expo start --clearでキャッシュをクリアするとすぐ直りました。
react-nativeからPickerが使えない等、APIが分離されているケースに遭遇。公式ドキュメントで確認し、@react-native-picker/pickerを別途インストールすることで解決。

まとめ

今回はほんの最初の一歩として、Expoプロジェクトを立ち上げて、1つの機能(ここでは簡単なテキストとボタン表示&画面遷移)を実現してみました。
まだまだ足りないところは山ほどありますが、「実機で画面が動く」状態にできると、次のステップへのモチベーションが上がります。

今後はUIを整えたり、データ保存、API連携などにも挑戦していく予定です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?