React Native:如何将本地路径的Lottie JSON文件作为LottieView源?
解决LottieView无法加载本地JSON动画文件的问题
我来帮你搞定这个问题——你尝试直接用本地文件路径作为LottieView的source.uri确实行不通,因为LottieView的uri参数主要是用来加载远程资源或者打包在应用内部的资源,对于文件系统里的本地文件,这种方式没办法正确解析。
可行的解决方案:读取文件内容转为JS对象
正确的做法是先通过react-native-fs读取本地JSON文件的内容,解析成JavaScript对象后,直接把这个对象传给LottieView的source属性。
完整代码示例
import RNFS from 'react-native-fs'; import LottieView from 'lottie-react-native'; import React from 'react'; // 你的本地动画文件路径 const localAnimationPath = '/Users/marlon/Library/Developer/CoreSimulator/Devices/8E0A092D0E86/data/Containers/Data/Application/AADD60D8DFAD/Documents/animation.json'; export default class AnimationComponent extends React.Component { state = { animationData: null, }; componentDidMount() { // 读取本地JSON文件 RNFS.readFile(localAnimationPath) .then(res => { // 将文件内容解析为JS对象 this.setState({ animationData: JSON.parse(res) }); }) .catch(err => { console.log('加载动画文件出错:', err); }); } render() { const { animationData } = this.state; // 动画数据加载完成前可以显示加载提示 if (!animationData) return <div>Loading...</div>; return ( <LottieView source={animationData} autoPlay loop style={{ width: 300, height: 300 }} /> ); } }
为什么这个方法有效?
LottieView的source属性不仅支持{ uri: ... }这种格式,还直接接受解析好的JSON对象。通过读取本地文件并解析成对象,我们直接给LottieView提供了它能直接识别的动画数据结构,自然就能正常渲染动画了。
内容的提问来源于stack exchange,提问作者Sebastian Auberger
相关产品推荐
相关产品推荐

