【问题标题】:How to Access Image in local JSON Array如何访问本地 JSON 数组中的图像
【发布时间】:2020-01-19 03:14:52
【问题描述】:
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,,,

【问题讨论】:

  • 看起来是对的,你有错误吗?还是只是img路径不对?
  • 使用 src={require(item.pic)} 而不是 source={require(item.pic)} 因为您需要的是本地图片,而不是网址图片。
  • @P4uB0rd4 in react native 你应该使用像这样的源 &lt;Image source={require('./assets/image.png')} /&gt; 如果你使用的是 react-natives Image 组件
  • 这看起来是正确的。我无法重现。请参阅:snack.expo.io/B1mJ1OJPr 我唯一的想法可能是您的图像路径错误,或者您的渲染方法没有被调用。你有什么错误吗?
  • @Patte 是的,出现这样的错误“第 31 行的无效调用:require(JSON.stringify(item.pic))”

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


【解决方案1】:

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

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

然后在 Hijama 的循环中创建 ${image}

附言我建议你重构你的变量名(使用 camelCase)

【讨论】:

    【解决方案2】:

    你不能像那样使用 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>
      );
    })};
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-02
      • 1970-01-01
      • 1970-01-01
      • 2015-04-03
      • 1970-01-01
      相关资源
      最近更新 更多