如何在React Native中使用dotLottie?

问题描述 投票:0回答:1

我如何在 React Native 中使用 dotlottie。我已将 json 文件压缩为 dotlottie 文件,但如何在 React Native 中渲染此 dotlottie。

https://dotlottie.io/

有什么办法可以实现这一点吗?

或者还有其他方法可以减少 json 文件大小吗?

react-native gif lottie
1个回答
0
投票

新的 npm 包刚刚发布。

安装:

npm install @lottiefiles/dotlottie-react-native

然后更新您的 Metro 配置以支持

.lottie
文件:

// metro.config.js
const { getDefaultConfig } = require('metro-config');

module.exports = (async () => {
  const {
    resolver: { sourceExts, assetExts },
  } = await getDefaultConfig();
  return {
    resolver: {
      assetExts: [...assetExts, 'lottie'],
    },
  };
})();

在您的项目中像下面一样使用它:

import { Button, StyleSheet, View } from 'react-native';
import { DotLottie, Mode, type Dotlottie } from '@lottiefiles/dotlottie-react-native';
import { useRef } from 'react';

export default function App() {
  const ref = useRef<Dotlottie>(null);

  return (
    <View style={styles.container}>
      <DotLottie
        ref={ref}
        source={require('../assets/animation.lottie')}
        style={styles.box}
        loop={false}
        autoplay={false}
      />
      <Button title="Play" onPress={() => ref.current?.play()} />
      <Button title="Pause" onPress={() => ref.current?.pause()} />
      <Button title="Stop" onPress={() => ref.current?.stop()} />
      <Button title="Loop" onPress={() => ref.current?.setLoop(true)} />
      <Button title="Speed" onPress={() => ref.current?.setSpeed(1)} />
      <Button
        title="FORWARD"
        onPress={() => ref.current?.setPlayMode(Mode.FORWARD)}
      />
      <Button
        title="REVERSE"
        onPress={() => ref.current?.setPlayMode(Mode.REVERSE)}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  box: {
    width: 200,
    height: 200,
    marginVertical: 20,
  },
});
© www.soinside.com 2019 - 2024. All rights reserved.