如何在 React Native 中播放 Lottie 动画片段(.json 文件)

Bel*_*oid 4 reactjs react-native react-native-ios lottie

我只想使用 Lottie View 在 React Native 中播放动画的一部分,长度约为 5 秒,而速度= {1} 我只想播放前 3 秒,然后转到下一个屏幕,代码如下

徽标屏幕.js:

import React from 'react';
import { StyleSheet, View, Image, TextInput, StatusBar, Text } from "react-native";
import Icons from 'react-native-vector-icons/Ionicons';
import LottieView from "lottie-react-native";

export default class ChatScreen extends React.Component {

  onAnimationFinish = () => {
    this.props.navigation.navigate("Login")
  }
  render () {
    return (
      <View style={styles.container}>
        <StatusBar barStyle="light-content" backgroundColor="#161f3d" />
        <View>
          <LottieView
            source={require('../assets/animations/lottie/MotionCorpse-Jrcanest.json')}
            style={{ justifyContent: "center", alignSelf: "center", height: "100%", width: "100%" }}
            autoPlay
            loop={false}
            speed={1}
            onAnimationFinish={this.onAnimationFinish}
          />
        </View>
      </View>
    )
  }
Run Code Online (Sandbox Code Playgroud)

小智 5

好吧,你可以通过多种方法来做到这一点,其中一种方法如下所示。

您可以使用 ref 手动播放,3 秒后重定向到下一个屏幕。

import React from 'react';
import { StyleSheet, View, Image, TextInput, StatusBar, Text } from "react-native";
import Icons from 'react-native-vector-icons/Ionicons';
import LottieView from "lottie-react-native";

export default class ChatScreen extends React.Component {

    componentDidMount() {
        this.anim.play();

        setTimeout(() => {
            this.props.navigation.navigate("Login")
        }, 3000);
    }

    render() {
        return (
            <View style={styles.container}>
                <StatusBar barStyle="light-content" backgroundColor="#161f3d" />
                <View>
                    <LottieView
                        source={require('../assets/animations/lottie/MotionCorpse-Jrcanest.json')}
                        style={{ justifyContent: "center", alignSelf: "center", height: "100%", width: "100%" }}
                        autoPlay={false}
                        loop={false}
                        speed={1}
                        ref={animation => { this.anim = animation; }} 
                    />
                </View>
            </View>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是,如果您知道确切的帧编号,那么您可以播放动画,直到该帧在 3 秒后完成。Lottie 文档中已经提到了这一点。

this.animation.play(30, 120);
Run Code Online (Sandbox Code Playgroud)