【问题标题】:React Native: How to load Lottie file from local pathReact Native:如何从本地路径加载 Lottie 文件
【发布时间】:2018-03-23 08:09:43
【问题描述】:

我使用react-native-fs 从远程服务器下载 Lottie 文件 (json)。将其保存到文件系统后,我得到一个类似/Users/marlon/Library/Developer/CoreSimulator/Devices/8E0A092D0E86/data/Containers/Data/Application/AADD60D8DFAD/Documents/animation.json 的路径。

现在有没有办法将该文件路径用作LottieView 的源?我尝试了各种方法,但都没有成功:

var path = '/Users/marlon/Library/Developer/CoreSimulator/Devices/8E0A092D0E86/data/Containers/Data/Application/AADD60D8DFAD/Documents/animation.json'

<LottieView source={{ uri: path }} />
<LottieView source={{ uri: 'file:/' + path }} />
<LottieView source={{ uri: 'file://' + path }} />
<LottieView source={{ uri: 'file://' + path, isStatic: true }} />

回答

只需将动画文件作为 javascript 对象传递给LottieView 即可。所以我现在所做的就是用react-native-fs 打开文件并用JSON.parse 解析它。最终结果如下:

RNFS.readFile(animations.congratsAnimation).then(res => {
    this.setState({ animation: JSON.parse(res) });
}
...
<LottieView source={this.state.animation} />

【问题讨论】:

  • 我不确定这是否是问题所在,但您的路径以 / 开头,它将创建类似 uri : 'file:///Users/....' 的路径尝试从路径中删除 / 并再次运行.
  • 那没有成功
  • 将 javascript 对象传递给 LottieView 完成了工作!谢谢!

标签: react-native lottie react-native-fs


【解决方案1】:

您不应硬编码下载的 json 文件路径,而应将其保存在设备的存储中,例如图片文件夹:

npm install --save react-native-fetch-blob

const { config, fs } = RNFetchBlob
RNFetchBlob.config({ path : RNFetchBlob.fs.dirs.DocumentDir + '/animation.png' +  })
.fetch('GET', 'http://example.com/file/whichever', {
    'Cache-Control' : 'no-store'
})
.then((res) => {
    // where the file is, keep it as state.animationPath
    this.setState(animationPath: res.path()) 
})

//render()
<LottieView source={{require(this.state.animationPath)}, isStatic: true }} />

【讨论】:

  • 我确实像你描述的那样获取文件,但不起作用的是&lt;LottieView source={{ uri: this.state.animationPath, isStatic: true }} /&gt;。你能确认这对你有用吗?
  • 我猜你的意思是&lt;LottieView source={{ uri: require(this.state.animationPath), isStatic: true }} /&gt;?当我这样做时,我得到Error: Unknown named module: '/Users/....。如果我尝试使用file:// 前缀,则独立。
【解决方案2】:

我认为您应该在引用资源路径时使用 require() 函数。 例如,您可以执行以下操作:

var path = require('/Users/marlon/Library/Developer/CoreSimulator/Devices/8E0A092D0E86/data/Containers/Data/Application/AADD60D8DFAD/Documents/animation.json');

<LottieView source = {require('/Users/marlon/Library/Developer/CoreSimulator/Devices/8E0A092D0E86/data/Containers/Data/Application/AADD60D8DFAD/Documents/animation.json')} />

【讨论】:

  • 据我所知require 在这里不起作用,因为它会在构建时解决其依赖关系,并且该文件在构建时将不存在
猜你喜欢
  • 1970-01-01
  • 2019-11-18
  • 1970-01-01
  • 2020-04-08
  • 1970-01-01
  • 1970-01-01
  • 2020-10-24
  • 2020-04-23
  • 2020-08-23
相关资源
最近更新 更多