感谢@Filipe 的回复,我得到了一些指导,并得到了一个可以满足您需求的工作示例。
就我而言,我在assets/markdown/ 文件夹中有一个.md 文件,该文件名为test-1.md
诀窍是获取文件的本地url,然后使用fetch API 将其内容作为string 获取。
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Markdown from 'react-native-markdown-renderer';
const copy = `# h1 Heading 8-)
| Option | Description |
| ------ | ----------- |
| data | path to data files to supply the data that will be passed into templates. |
| engine | engine to be used for processing templates. Handlebars is the default. |
| ext | extension to be used for dest files. |
`;
export default class App extends React.Component {
constructor(props) {
super(props)
this.state = {
copy: copy
}
}
componentDidMount() {
this.fetchLocalFile();
}
fetchLocalFile = async () => {
let file = Expo.Asset.fromModule(require("./assets/markdown/test-1.md"))
await file.downloadAsync() // Optional, saves file into cache
file = await fetch(file.uri)
file = await file.text()
this.setState({copy: file});
}
render() {
return (
<Markdown>{this.state.copy}</Markdown>
);
}
}
编辑:为了摆脱错误
无法从“App.js”解析“./assets/markdown/test-1.md”
您需要将@Filipe 的 sn-p 的 packagerOpts 部分添加到您的 app.json 文件中。
app.json
{
"expo": {
...
"assetBundlePatterns": [
"**/*"
],
"packagerOpts": {
"assetExts": ["md"]
},
...
}
}
编辑 2:
回答@Norfeldt 的评论:
虽然我在处理自己的项目时使用react-native init,因此我对Expo 不是很熟悉,但我得到了这个Expo Snack,它可能会为您提供一些答案:https://snack.expo.io/Hk8Ghxoqm。
由于读取非 JSON 文件的问题,它不适用于博览会小吃,但如果您愿意,可以在本地进行测试。
使用file.downloadAsync() 将阻止应用向在该应用会话中托管您的文件的服务器进行 XHR 调用(只要用户不关闭并重新打开应用)。
如果您更改文件或修改文件(模拟调用Expo.FileSystem.writeAsStringAsync()),只要您的组件重新渲染并重新下载文件,它就应该显示更新的内容。
每次关闭并重新打开您的应用程序时都会发生这种情况,因为就我而言,file.localUri 不会在每个会话中持续存在,因此您的应用程序每次都会至少调用一次 file.downloadAsync()打开。所以显示更新的文件应该没有问题。
我还花了一些时间来测试使用fetch 与使用Expo.FileSystem.readAsStringAsync() 的速度,它们的平均速度是相同的。通常Expo.FileSystem.readAsStringAsync 的速度快了约 200 毫秒,但在我看来,这并不是什么大问题。
我创建了三种不同的方法来获取同一个文件。
export default class MarkdownRenderer extends React.Component {
constructor(props) {
super(props)
this.state = {
copy: ""
}
}
componentDidMount() {
this.fetch()
}
fetch = () => {
if (this.state.copy) {
// Clear current state, then refetch data
this.setState({copy: ""}, this.fetch)
return;
}
let asset = Expo.Asset.fromModule(md)
const id = Math.floor(Math.random() * 100) % 40;
console.log(`[${id}] Started fetching data`, asset.localUri)
let start = new Date(), end;
const save = (res) => {
this.setState({copy: res})
let end = new Date();
console.info(`[${id}] Completed fetching data in ${(end - start) / 1000} seconds`)
}
// Using Expo.FileSystem.readAsStringAsync.
// Makes it a single asynchronous call, but must always use localUri
// Therefore, downloadAsync is required
let method1 = () => {
if (!asset.localUri) {
asset.downloadAsync().then(()=>{
Expo.FileSystem.readAsStringAsync(asset.localUri).then(save)
})
} else {
Expo.FileSystem.readAsStringAsync(asset.localUri).then(save)
}
}
// Use fetch ensuring the usage of a localUri
let method2 = () => {
if (!asset.localUri) {
asset.downloadAsync().then(()=>{
fetch(asset.localUri).then(res => res.text()).then(save)
})
} else {
fetch(asset.localUri).then(res => res.text()).then(save)
}
}
// Use fetch but using `asset.uri` (not the local file)
let method3 = () => {
fetch(asset.uri).then(res => res.text()).then(save)
}
// method1()
// method2()
method3()
}
changeText = () => {
let asset = Expo.Asset.fromModule(md)
Expo.FileSystem.writeAsStringAsync(asset.localUri, "Hello World");
}
render() {
return (
<ScrollView style={{maxHeight: "90%"}}>
<Button onPress={this.fetch} title="Refetch"/>
<Button onPress={this.changeText} title="Change Text"/>
<Markdown>{this.state.copy}</Markdown>
</ScrollView>
);
}
}
只需在三者之间交替以查看日志中的差异。