我使用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 }} />
ANSWER
将动画文件作为javascript对象传递给LottieView
即可。所以我现在做的是用react-native-fs
打开文件并用JSON.parse
解析它。最终结果如下:
RNFS.readFile(animations.congratsAnimation).then(res => {
this.setState({ animation: JSON.parse(res) });
}
...
<LottieView source={this.state.animation} />
答案 0 :(得分:0)
我认为您应该在引用资源路径时使用 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')} />
答案 1 :(得分:0)
您不应该对下载的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 }} />