react.jsでもおなじみのモーダル機能をreact-nativeでも付けたいと思い色々探してみた結果
react-native-modalが分かりやすくて良さげだったので試してみました。
react.jsとreact-nativeとじゃライブラリの勝手が違うかと思ったのですが、割と簡単に実装できたので
今開発している自分用アプリに組み込んでもいいんじゃないかという結論に至りました。
以下インストール方法と実際にモーダルを表示するまでの方法
①まず、npm i react-native-modalでライブラリをインストール。
②使いたいページにimport Modal from “react-native-modal”;でインポートする。
③viewの中にModalを追加する
<View style={pageStyle}> <MyButton press={() => {this.start()}} text="let,s push!!"/> <Modal isVisible={this.state.isvisible}> <View style={{ flex: 1, justifyContent: 'center', backgroundColor: "#fff", alignItems: 'center', }}> <Text>サンプル</Text> <Button title="Close modal" onPress={() => {this.start()}}/> </View> </Modal> </View></pre> <pre>
ModalのisVisibleプロパティでtrue/falseの判定を監視し、ボタン(start関数)が押されて
isvisibleのstateが更新されたらモーダルが表示される仕組みになっています。
全体像はこちら↓
import React, { Component } from 'react'; import { View,Text,Button } from 'react-native'; import Modal from "react-native-modal"; const pageStyle = { justifyContent: 'center', flex: 1, } class main extends Component { constructor(props) { super(props); this.state = { isvisible: false }; } start(){ this.setState({ isvisible: !this.state.isvisible }); } render() { return ( <View style={pageStyle}> <MyButton press={() => {this.start()}} text="let,s push!!"/> <Modal isVisible={this.state.isvisible}> <View style={{ flex: 1, justifyContent: 'center', backgroundColor: "#fff", alignItems: 'center', }}> <Text>サンプル</Text> <Button title="Close modal" onPress={() => {this.start()}}/> </View> </Modal> </View> ); } } <pre>
今までのreact-nativeライブラリよりは割と素直に動いてくれました。
一回入れてみてそこそこ慣れてきたので、TextだけでなくDatePickerや画像を入れて遊んでみたいと思います。