Expo:AndroidとWeb両対応のアプリを作ってみる
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiSutRv6L5RQqJdXp7Zc1JNAADwmgX3m0KMH52WympELsarGJcsKzwAp-ve1EcPOWa-iAl6XFcJX4yB6fwOkrkUPLCjetYZqzvL6GyJus2W4AkTy8-bKfVkD-48JXzLU31IivMXiYDJbJ0lDGn5-O4NV9AY7uP8OfHR18nuRmNIWrqIJ-B0fZc9TjFV8A/s400/eto_usagi_fukubukuro.png
手元に iPad はあるものの最終的に ipa をビルドしたりできる環境がない 開発だけなら Expo Go や Expo SDK を使うとうまくごまかしたりできるっぽい
AndroidとWeb両対応なアプリを作る
画面内にダイアログを表示するボタンを設置する
使用したコンポーネントや仕組みは以下
OSネイティブな見た目のボタンを表示する組み込みのコンポーネント。
OSネイティブな見た目のダイアログを表示する組み込みのコンポーネント。
Alert.alert で ハンドラになる関数を生成できるので onPress に設定すると使用できる
code:ts
// 初期化
const showNativeDialog = () =>
Alert.alert('Message', message, text: 'OK' })
// 使うときは
<Button title="Show dialog" onPress={showDialog}></Button>
Platform.OS を使うと android ios web などの文字列で環境を判定できる
両対応なアプリを作るには・・・
React Native が標準対応していない仕組みを使う場合は、環境ごとに対応するコードを書く必要がある。
逆を言うとそれさえすれば、見た目を実現するコードは同じものが使えるということになる。
実際に書いたコード
code:ts
import React from 'react'
import { StatusBar } from 'expo-status-bar'
import { Platform, StyleSheet, View, Button, Alert, Text } from 'react-native'
export default () => {
const message = This is a sample dialog.
const showNativeDialog = () =>
Alert.alert('Message', message, text: 'OK' })
const showWebDialog = () => {
alert(message)
}
const showDialog = () => {
if (Platform.OS === 'web') {
return showWebDialog()
}
showNativeDialog()
}
return (
<View style={styles.container}>
<Text style={styles.environmentText}>Environment: {Platform.OS}</Text>
<Button title="Show dialog" onPress={showDialog}></Button>
<StatusBar style="auto" />
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
environmentText: {
paddingBottom: 32,
},
})
実行結果
Android版
React Native 自体が対応する機能なので、OSの見た目に近いUIで表示される
https://gyazo.com/5c139d11e212569b1395a7fc544a2846
Web版
Alert は対応していないので、ブラウザ標準の alert で迂回。
https://gyazo.com/9e321dc5e6c7c4491b681c37c647a4f0