如何访问本地JSON数组中的图像

时间:2019-09-18 08:16:43

标签: javascript arrays json react-native react-native-swiper

Hijama = [
{
  name: 'Body Back',
  pic: '../Images/BackSide.png',
},
{
  name: 'Body Front',
  pic: '../Images/images.jpg',
},];

//在这里我要渲染我的照片

     render_swiper_data = () => {
return this.Hijama.map((item, index) => {
  console.log('check', item);
  return (
    <View key={index}>
      <Text>{item.name}</Text>
      <Image
        source={require(item.pic)}
        style={{
          height: '100%',
          width: '100%',
        }}
      />
    </View>
  );
})};

///现在我的问题是如何同时尝试Require和uri,

2 个答案:

答案 0 :(得分:1)

您不能使用require这样的。 react-native无法读取。 因此您必须像这样存储所有本地图像位置:

Hijama = [
{
  name: 'Body Back',
  pic: require('../Images/images.jpg'),
},
{
  name: 'Body Front',
  pic: require('../Images/images2.jpg')
},];

,然后在您的代码中使用它:

     render_swiper_data = () => {
return this.Hijama.map((item, index) => {
  console.log('check', item);
  return (
    <View key={index}>
      <Text>{item.name}</Text>
      <Image
        source={item.pic}
        style={{
          height: '100%',
          width: '100%',
        }}
      />
    </View>
  );
})};

答案 1 :(得分:0)

如果所有图像中都有一些常量,则可以使用模板文字。

src={require(`./Images/${image}.png`)}

${image}放入您的Hijama循环中。

p.s。我建议您重构变量名(使用camelCase)