[英]How to post image in react-native with require and variable in the path
[英]React Native, how to add a variable inside image link with require function
我將圖像本地存儲在項目文件夾中,並且我想在圖像源(帶有要求)中添加一個變量(nature.png),所以我這樣做了
let i = 'natrue';
let imagePath = require('../asset/gallery/image/');
return (
<View >
<Image source={{imagePath} + i + '.png'}/>
</View>
但我得到了一個錯誤:
text string must be rendered within a text component
我不想這樣做(工作正常),因為我有 100 多個圖像:
<Image source={require('../asset/gallery/image/nature.png')} />
Unfournately requirejs
模塊不能那樣工作
您必須完全創建字符串或創建一個將key
映射到圖像的對象。 這也是遵循的最佳實踐。
您可以創建一個名為 image.js 的文件並從那里導出所有圖像,
例如
// image.js
const BASE_URL = "../asset/gallery/image/";
export default {
nature:require(`${BASE_URL}nature.png`),
}
在你的組件中,
import Images from "src/images";
...
<>
<Image src={Images.nature}/>
</>
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.