Works by

Ren's blog

@rennnosuke_rk 技術ブログです

【React Native】react-native-swiperで画面スワイプを実装する

react-native-swiper

React Nativeでスワイプ画面遷移が可能になるreact-native-swiperを試してみました。

github.com

Usage

1. 前回の記事に従い、create-react-native-appをインストール

rennnosukesann.hatenablog.com

2. create-react-native-appプロジェクトを作成
$ create-react-native-app react-native-swiper-app
$ cd react-native-swiper-app
3. react-native-swiperをインストール
$ npm install --save react-native-swiper
4. デプロイ
$ npm start

Source

サンプルコードをもとにApp.jsを修正しました。

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Swiper from 'react-native-swiper';

const styles = StyleSheet.create({
  slide: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#9DD6EB',
  },
  text: {
    color: '#fff',
    fontSize: 30,
    fontWeight: 'bold',
  }
})

export default class App extends React.Component {
  render() {
    return (
      <Swiper showsButtons={true}>
        <View style={styles.slide}>
          <Text style={styles.text}>First Page</Text>
        </View>
        <View style={styles.slide}>
          <Text style={styles.text}>Second Page</Text>
        </View>
        <View style={styles.slide}>
          <Text style={styles.text}>Third Page</Text>
        </View>
      </Swiper>
    );
  }
}

Swiperの小要素としてView複数設定することで、設定した小要素間をスワイプで遷移可能になります。

Demo

f:id:rennnosukesann:20180528223553g:plain:w300

Options

スワイプ方向を垂直にする

horizontal属性でスワイプ方向を変更できます。
デフォルトはtrue

<Swiper horizontal={false}>
 ...
</Swiper>

f:id:rennnosukesann:20180528225303g:plain:w300

スワイプをループさせない

loogfalseにすると、末尾ページから先頭ページへのスワイプを抑止できます。デフォルトはtrue

<Swiper showButton={true} loop={true}>
 ...
</Swiper>
自動スワイプ

autoplaytrueにすると、スワイプが自動化されます。
デフォルトはfalse

 <Swiper autoplay={true}>
</Swiper>

参考

github.com