React Native Image uri 不起作用
React Native Image uri doesn't work
我试图显示本地文件中的图像,所以我尝试这样做
<Image
source={{uri:'../../assets/img_src/BTI.jpg'}}
style={{height:150,width:150}}
/>
我的容器组件似乎获得了高度和宽度,但没有加载图像。所以我试试这个
<Image
source={require('../../assets/img_src/BTI.jpg')}
style={{height:150,width:150}}
/>
它工作得很好,不幸的是,据我所知,如果我想先操作地址文件并将其存储到变量中,我不能使用这个实现。
示例:
const imgSrc = `../../assets/${data.image}`;
其中 data.image = 'img_src/BTI.jpg'。
我尝试删除 android 工作室中我的 android 模拟器上的所有数据,但结果仍然相同。难道我做错了什么?有没有更好的实现方式?
非常感谢:)
无法 require()
动态路径是 React Native 的预期行为,打包程序需要提前知道路径 - 请参阅 React Native issues
我们在项目中遇到了这个问题,我们将图像 URL 存储在我们的数据库中,并希望在应用程序中连接字符串以获取本地存储图像的路径。正如您所发现的,这是行不通的。您可能会发现我们的解决方法很有用。
在我们的 /images
文件夹中,我们创建了一个新的 images.js
文件,它只是导出一个对象,其键映射到我们所有的本地图像路径,就像这样
export const Images = {
image1: require('./image1.png'),
image2: require('./image2.png'),
image3: require('./image3.png'),
};
现在包装商提前知道了所有路径并且很高兴。然后我们向 DB 项添加了一个 imageKey
并使用它而不是绝对路径。要抓取图像,我们只是做了
import { Images } from '../images/images';
// get your image key e.g. passed down through props
const img = Images[imageKey];
...
render() {
...
<Image source={img} />
...
}
可能不适合您的确切用例,但希望您可以使用它。
我试图显示本地文件中的图像,所以我尝试这样做
<Image
source={{uri:'../../assets/img_src/BTI.jpg'}}
style={{height:150,width:150}}
/>
我的容器组件似乎获得了高度和宽度,但没有加载图像。所以我试试这个
<Image
source={require('../../assets/img_src/BTI.jpg')}
style={{height:150,width:150}}
/>
它工作得很好,不幸的是,据我所知,如果我想先操作地址文件并将其存储到变量中,我不能使用这个实现。 示例:
const imgSrc = `../../assets/${data.image}`;
其中 data.image = 'img_src/BTI.jpg'。 我尝试删除 android 工作室中我的 android 模拟器上的所有数据,但结果仍然相同。难道我做错了什么?有没有更好的实现方式?
非常感谢:)
无法 require()
动态路径是 React Native 的预期行为,打包程序需要提前知道路径 - 请参阅 React Native issues
我们在项目中遇到了这个问题,我们将图像 URL 存储在我们的数据库中,并希望在应用程序中连接字符串以获取本地存储图像的路径。正如您所发现的,这是行不通的。您可能会发现我们的解决方法很有用。
在我们的 /images
文件夹中,我们创建了一个新的 images.js
文件,它只是导出一个对象,其键映射到我们所有的本地图像路径,就像这样
export const Images = {
image1: require('./image1.png'),
image2: require('./image2.png'),
image3: require('./image3.png'),
};
现在包装商提前知道了所有路径并且很高兴。然后我们向 DB 项添加了一个 imageKey
并使用它而不是绝对路径。要抓取图像,我们只是做了
import { Images } from '../images/images';
// get your image key e.g. passed down through props
const img = Images[imageKey];
...
render() {
...
<Image source={img} />
...
}
可能不适合您的确切用例,但希望您可以使用它。