素のJavaScriptでも用意されているalert関数のように、画面にポップアップを表示してユーザーに選択を求めることができるReact NativeのAlertコンポーネントの使い方についてまとめる。
Alertコンポーネントの基本の使い方
まずはコードを見てみよう。
Alert.alert( 'Alert Title', 'A or B ???', [ {text: 'A', onPress: () => this.funcA()}, {text: 'B', onPress: () => this.funcB()}, ], { cancelable: false } )
alertメソッドの第一引数にダイアログのタイトルを、第二引数に説明文を指定する。
第三引数には配列形式でボタン表示テキスト、ボタン押下時の動作を指定する。
デモアプリ
Alertコンポーネントを使ったデモアプリを用意した。
ダイアログには3つの選択肢(Blue, Red, Green)が用意されており、それぞれボタンをタップすると画面の背景色が切り替わるというシンプルなものだ。
なお、Redボタンにはオプションとして、キャンセルボタン用のスタイルを適用している。
import React, { Component } from 'react'; import { View, Button, Alert } from 'react-native'; export default class App extends Component { constructor() { super(); this.state = { color: '#009' } } changeBGColor(hex) { this.setState({color: hex}); } showAlert() { Alert.alert( 'Alert Title', 'My Alert Msg', [ {text: 'Blue', onPress: () => this.changeBGColor('#009')}, {text: 'Red', onPress: () => this.changeBGColor('#900'), style: 'cancel'}, {text: 'Green', onPress: () => this.changeBGColor('#090')}, ], { cancelable: false } ) } render() { const { color } = this.state; return( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: color }}> <Button color={"#FFF"} onPress={() => {this.showAlert()}} title={"show Alert"} /> </View> ); } }
expo startでアプリを実行し、動作を確認してみる。


