ReactNative
Build native mobile apps using JavaScript and React
まずは公式ページの Quick Startを試してみたいと思います。
環境構築
ReactNativeアプリを構築するのに2種類ある。
- Expo
Expoは新しいReact Nativeアプリケーションを構築する最も簡単な方法です。
ネイティブコードを構築するためのツールをインストールまたは設定することなくプロジェクトを開始できます
XcodeやAndroid Studioのインストールは不要です
- Building project with Native Code
- react-native-cliなどを使って構築していく
今回は触ってみる程度なので、Expoを使ってサンプルを動かしてみたいと思います。
環境
- node: 9.5.0
- expo-cliのインストール
$ npm install -g expo-cli
- サンプルプロジェクトを作成し起動
$ expo init expo-sample
? Choose a template:
blank
minimum dependencies to run and an empty root component
❯ tabs
several example screens and tabs using react-navigation
? Choose which workflow to use: managed
? Yarn v1.3.2 found. Use Yarn to install dependencies? Yes
templateは tabs
、workflowは managed
、Yarn を使うは Yes
を選択 し
プロジェクトの作成と起動を行います。
$ cd expo-sample
$ yarn start
無事に起動できたっぽい
試しに Run on iOS simulator
をクリックしてiOSシュミレータで起動してみると
Expoのクライアントアプリがインストールされ、アプリが起動されました。
実機の場合は Androidだと ExpoアプリをインストールしてQRコードを読み取ればOKでした。
iOSの場合、ExpoアプリをインストールしてリンクをメールかSMSで送信し、
Safari経由でdeeplinkを開くとアプリが起動されました!
参考URL
- Expo環境構築
実装
ちゃんとHot Reloadingされるか試してみる
試しに Change this text and your app will automatically reload.
となっている箇所を変更してみます...
普段iOS/Androidをネイティブで開発している人にとっては嬉しい
Typescript導入
型があるのは何かと便利なので、そのままTypescriptを導入します。
$ yarn add typescript --dev
$ ./node_modules/.bin/tsc --init
$ mv App.js App.tsx
ひとまず↑だけでも動作しましたが、(簡単 )
@types
などもインストールして環境を整えます。
$ yarn add @types/react @types/react-native @types/expo --dev
tsconfig.json
を修正する。
{
"compilerOptions": {
...
"jsx": "react-native"
...
}
}
ListViewを追加
最後にアプリ開発で頻繁に使うListViewを試してみたいと思います。
ここを参考に実装
import * as React from "react";
import { FlatList, StyleSheet, Text, View } from "react-native";
interface IListData {
key: string;
}
const listData: IListData[] = [
{ key: "Devin" },
{ key: "Jackson" },
{ key: "James" },
{ key: "Joel" },
{ key: "John" },
{ key: "Jillian" },
{ key: "Jimmy" },
{ key: "Julie" }
];
type Props = {};
export default class App extends React.Component<Props> {
render() {
return (
<View style={styles.container}>
<FlatList
data={listData}
renderItem={({ item }) => <Text style={styles.item}>{item.key}</Text>}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 30,
backgroundColor: "#fff"
},
item: {
padding: 10,
fontSize: 18,
height: 44
}
});
ちゃんとTypescriptの型付けもされていて、無事一覧が表示されました。