我需要将 JSON 文件中的图像放到我的 React Native 页面中。下面是我的代码:
<View style={{ flexDirection: 'row', alignItems:'center' }}>
<Image source={{item.image}} style = {styles.imageView}/>
<View style={{ flex: 1, alignItems: "center"}}>
<Text style={styles.Address1}>{item.addr} </Text>
</View>
</View>
我可以从我的 JSOn 文件中读取其他内容,例如 item.addr 来自 json 文件,但不确定如何读取图像。我试过这样写我的 json 文件:
{
"addr": "124 test drive, Ring road",
"phone": "(951)-955-6200",
"LatL":"33.977880",
"Long2":"-117.373423",
"cLat": "33.931989",
"cLong": "-117.409222",
"Online": "https://www.test.org",
"image" : "require(\"CAC.png\")"
}
我也试过在我的 JSON 文件中写像下面这样的图像
"image" : "require('../images/CAC.png')"
看来,它正在读取空白图像:下面是屏幕截图:
下面的代码是有效的,但在这种情况下,我正在写一个常量图像而不是从 json 文件中读取。
<Image source={require('../images/CAC.png')} style = {styles.imageView}/>
我的代码位于名为 Modules 的目录中,该目录位于项目目录目录中。我的项目名称是 test,我的 Json 文件位于名为 Reducers 的目录中,reducers 也位于项目目录中,我的图像位于名为 images 的目录中,该目录也位于项目目录中。下面是路径:
c:\MobileApplication\test\Modules\ServiceListDetails.js
c:\MobileApplication\test\reducers\ServiceDetails.json
c:\MobileApplication\test\images\CAC.png
我的项目名称是test。下面是我的 imageView 样式
imageView:{
width:'30%',
height:100,
margin:7,
borderRadius: 7
},
任何帮助将不胜感激。
最佳答案
请确保您的图像名称在您的 json 文件中是正确的。例如,.png 而不是 .PNG,然后你需要这样的东西:
首先创建一个组件来加载你的图标:
c:\MobileApplication\test\Modules\Icons.js
exports.CAC = require('../assets/images/CAC.png');
exports.CAD = require('../assets/images/CAD.png');
exports.CAE = require('../assets/images/CAE.png');
其次在你的组件中导入你的图标:
c:\MobileApplication\test\Modules\ServiceListDetails.js
import Icons from './Icons';
import resources from './ServiceDetails.json';
最后:
<Image source={Icons[resources.image]} style = {styles.imageView}/>
现在您必须用您想要的代码更改 o json。
"image": "CAC"
}
或者
"image": "CAD"
}
或者
"image": "CAE"
}
关于reactjs - 如何将图像从 JSON 文件放到 React Native Js 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52322579/