注意事項
リアクトネイティブは、JavaScriptとReactを使ってネイティブモバイルアプリを書くという、ほとんどのフロントエンド開発者にとってなじみのないものではありません。
直面する問題
RN expo-cliを使ってアプリを書くには2つの方法があります。1つはcreate-react-native-appを使う方法です。Expoを使う方法の利点は、iOS Androidのコンパイル環境を設定する必要がないこと、そして公開するときにアプリを実行するためにExpoをインストールする必要があることです。
そしてexpoは型に縛られることなく、純粋なreact-nativeプロジェクトと相互運用が可能です。
環境の準備
1.expo-cliのインストール
npm install expo-cli --global
2、プロジェクトの作成
expo init my-new-project
テンプレートには、ホスト型ワークフローとベア型ワークフローの2種類があります:
expo init simple-project
? Choose a template:
----- Managed workflow -----
❯ 空のキャンバスのようにきれいなミニマムアプリを作る。
blank (TypeScript) same as blank but with TypeScript configuration
tabs several example screens and tabs using react-navigation
----- Bare workflow -----
minimal bare and minimal, just the essentials to get you started
minimal (TypeScript) same as minimal but with TypeScript configuration
3.プロジェクトの立ち上げ
cd my-new-project
expo start
4、プロジェクトのプレビュー
プロジェクトが起動したら、AppStoreでExpo ClientモバイルクライアントをダウンロードしてQRコードをスキャンするか、ターミナルwでブラウザを起動し、aまたはiを入力してAndroidまたはiOSエミュレータを起動します。
最初のアプリの作成
このアプリはデフォルトでイメージを表示し、ユーザーがイメージを選択して共有することができます。
ディレクトリのapp.jsを修正します。
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<Text>To share a photo from your phone with a friend, just press the button below!</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
ブラウザや携帯電話のExpoでプレビューでき、インターフェースの真ん中に表示されるテキストを見ることができます。
このテキストは少し小さすぎるので、スタイルを追加してテキストを増やすことができます:
<Text style={{color: '#888', fontSize: 18}}>
イメージの追加
React NativeでTextコンポーネントを使用してテキストを表示した後は、Imageコンポーネントを使用してイメージを表示できます。Imageコンポーネントを作成するときは、幅と高さを明示的に指定する必要があります。
ファイルインポートにImageコンポーネントを追加し、静的イメージlogo.pngをオブジェクトロゴとしてインポートします:
import { Image, StyleSheet, Text, View } from 'react-native';
import logo from './assets/logo.png';
このコンポーネントは、Viewコンポーネント内の1行目に追加し、Sourceにロゴオブジェクトを指定します:
<Image source={logo} style={{ width: 305, height: 159 }} />
完成した文書は以下の通り。
import React from 'react';
import { Image, StyleSheet, Text, View } from 'react-native';
import logo from './assets/logo.png';
export default function App() {
return (
<View style={styles.container}>
<Image source={logo} style={{ width: 305, height: 159 }} />
<Text style={{color: '#888', fontSize: 18}}>
To share a photo from your phone with a friend, just press the button below!
</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
ボタンの追加
TouchableOpacity コンポーネントとスタイル付きテキストを使用して、独自のカスタムボタンを作成します。
まずこのコンポーネントをインポートします:
import { Image, StyleSheet, Text, View,TouchableOpacity } from 'react-native';
Imageコンポーネントの後にこのコンポーネントを追加します:
<TouchableOpacity
onPress={() => alert('Hello, world!')}
style={{ backgroundColor: 'blue' }}>
<Text style={{ fontSize: 20, color: '#fff' }}>Pick a photo</Text>
</TouchableOpacity>
イベントコード内のTouchableOpacityプロパティonPressの一つは、直接フックすることができ、ここではアラートを表示することです。
書き込み後のコード:
import React from 'react';
import { Image, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<Image source={{ uri: 'https://../.ng' }} style={styles.logo} />
<Text style={styles.instructions}>
To share a photo from your phone with a friend, just press the button below!
</Text>
<TouchableOpacity
onPress={() => alert('Hello, world!')}
style={{ backgroundColor: 'blue' }}>
<Text style={{ fontSize: 20, color: '#fff' }}>Pick a photo</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
logo: {
width: 305,
height: 159,
marginBottom: 20,
},
instructions: {
color: '#888',
fontSize: 18,
marginHorizontal: 15,
marginBottom: 10,
},
});
イメージの選択
これまで、ReactとReact Nativeのコードをアプリで使用してきました。Reactはコンポーネントを構築する優れた方法を提供し、React NativeはiOS、Android、Webで動作するビルド済みのコンポーネント(View、Textなど)を提供します、React Nativeはイメージピッカーを提供していません。このため、Expo-image-pickerというExpoライブラリを使用できます。
このコンポーネントを最初にインストールする必要があります:
expo install expo-image-picker
コンポーネントのインポート、イベントハンドラのフックアップ、イベントハンドラの記述:
export default function App() {
const [selectedImage, setSelectedImage] = React.useState(null);
let openImagePickerAsync = async () => {
let permissionResult = await ImagePicker.requestCameraRollPermissionsAsync();
if (permissionResult.granted === false) {
alert('Permission to access camera roll is required!');
return;
}
let pickerResult = await ImagePicker.launchImageLibraryAsync();
if (pickerResult.cancelled === true) {
return;
}
setSelectedImage({ localUri: pickerResult.uri });
};
if (selectedImage !== null) {
return (
<View style={styles.container}>
<Image
source={{ uri: selectedImage.localUri }}
style={styles.thumbnail}
/>
</View>
);
}
return (
<View style={styles.container}>
{/* Our logo, instructions, and picker button are hidden here to keep the example brief */}
</View>
);
}
const styles = StyleSheet.create({
/* Other styles hidden to keep the example brief... */
thumbnail: {
width: 300,
height: 300,
resizeMode: "contain"
}
});
Reactフックは、クラスを使用せずにステートのようなリアクトのコア機能にアクセスする新しい方法です。あなたのケースでは、onClickプロップでカウンタを直接指定せずに、ハンドラ関数でカウンタを直接インクリメントしたい場合、次のようにできます。
...
const [count, setCounter] = useState(0);
const [moreStuff, setMoreStuff] = useState(...);
...
const setCount = () => {
setCounter(count + 1);
setMoreStuff(...);
...
};
onClickイベント内。
<button onClick={setCount}>
Click me
</button>
useState(0)の引数である0は、ステートオブジェクトの初期値を表し、関数は、最初の引数であるcountがカウンタの現在の状態であり、setCounterがカウンタの状態を更新するためのメソッドであるタプルを返します。setCounterメソッドは、countの状態を更新するためにどこでも使用することが可能です。この場合、setCount関数の内部で、より多くのことを行うことができます。フックを使用するアイデアは、より多くの機能を持つコードを保持できるようにすることであり、それらが必要でない/必要である場合は、クラスベースのコンポーネントを避けることができます。
まとめ
この記事では、Expo環境を構築し、RN組み込みコンポーネントとExpoコンポーネントを使用した、イメージの表示とイベントの処理を行う簡単なアプリを作成します。これにより、Expo開発の世界に足を踏み入れることができます。