こんにちは、nukkyです。
今回はReact Nativeでよりリッチなアプリを作成するためにアニメーションを扱うライブラリ「react-native-animatable」と「lottie-react-native」を使ってみたいと思います。
インストールしたいプロジェクトで以下のコマンドを実行します。
npm install react-native-animatable --save
react-native-animatableをインポートします。
import * as Animatable from 'react-native-animatable';
アニメーションしたいコンポーネントに対して以下のようにするだけでアニメーションが実行されます。
<Animatable.Text animation="zoomInUp">Zoom me up, Scotty</Animatable.Text>
アニメーションをループしたい場合は以下、
<Animatable.Text animation="slideInDown" iterationCount={5} direction="alternate">Up and down you go</Animatable.Text> <Animatable.Text animation="pulse" easing="ease-out" iterationCount="infinite" style={{ textAlign: 'center' }}>❤️</Animatable.Text>
React Nativeのrefを使ってユーザーイベントが発生した時、アニメーションが実行されるように作れます。
// インポート import * as Animatable from 'react-native-animatable'; export default class Page extends React.Component<Props, State> { private AnimationRef; render() { // 中略 return ( <TouchableWithoutFeedback onPress={this._onPress}> <Animatable.View ref={ref => (this.AnimationRef = ref)}> <Text>Bounce me!</Text> </Animatable.View> </TouchableWithoutFeedback> ); } private _onPress = () => { this.AnimationRef.bounce(); } }
アニメーションはreact-native-animatableの公式githubでアニメーション例と一緒に確認できます。
https://github.com/oblador/react-native-animatable
使えるアニメーションで代表的なのは下記になります。まだまだ使用できるアニメーションはあるので公式で確認してみてください。
react-native-animatableはコンポーネントに対してアニメーションを行うライブラリでしたが、ローディング画面やスプラッシュなどでgifのようなアニメーションを簡単に実装できる「lottie-react-native」も使ってみたいと思います。
LottieはAfter Effectsで作成したアニメーションを、Bodymovinというオープンソースの拡張機能を使ってjson形式にエクスポートされたアニメーションデータを使用します。
アニメーションがjson形式なので、クロスプラットフォームで動かしやすい、ファイルサイズが大きくなりにくい、ネットワーク経由でも読み込みが可能になる、キャッシュを効かせやすい、など、様々なメリットがあります。また、LottieはAndroid、iOS、Web、React Nativeで扱うことができ「lottie-react-native」はその名の通りLottieをReact Nativeで扱うためのライブラリになります。
インストールしたいプロジェクトで以下のコマンドを実行します。
npm i --save lottie-react-native
インストールが完了したら以下のコマンドを実行します。
react-native link
アニメーション用のjsonファイルを準備します。LottieFilesというサイトからサンプルを取得できるのでこちらから使用していきます。使用するアニメーションが決まりましたら「assets」以下に配置してください。
まずはライブラリと上記で配置したjsonをインポートします。
import LottieView from 'lottie-react-native'; import loading from '../assets/lottie/sample.json';
lottie-react-nativeでは、LottieViewコンポーネントを呼び出しアニメーションさせます。アニメーション発火のタイミングで使用するので、refで参照を付けておきます。
<LottieView // 中略 ref={(refs) => { this.loadingAnimation = refs; }} source={sample} />
任意のタイミングでアニメーションを発火させます。今回はcomponentDidMountのタイミングでアニメーションを発火させています。このコードだけで、アニメーションを実装できます。簡単ですね!
componentDidMount() { if (this.loadingAnimation) this.loadingAnimation.play(); }
やはりアニメーションをさせるとグッとアプリぽくなって良いと思います。