【问题标题】:Not able to render image in React Native无法在 React Native 中渲染图像
【发布时间】:2019-12-11 11:46:44
【问题描述】:

我正在尝试从我的 react-native 应用程序中的本地文件夹加载 JPG 图像。

图像存储在资产文件夹中,我试图在图像标签中呈现该文件夹

这是我的 JSON 对象

  {
    title: 'Device 2',
    image: '../assets/imgs/device_default.jpg',
    cta: 'View device',
    mac: '1234-xxxx-xxxx-5678'
  },

这是我的代码

<Block flex style={imgContainer}>
   <Image source={{uri: item.image}} style={imageStyles} />
</Block>

这里的 item 包含 props 值。我可以迭代其他值,例如 title 和 mac

但无法渲染图像。

谁能帮我解决这个问题?

【问题讨论】:

    标签: react-native react-native-android


    【解决方案1】:

    JSON

        title: 'Device 2',
        src : require('../assets/imgs/device_default.jpg'),
        cta: 'View device',
        mac: '1234-xxxx-xxxx-5678'
      },
    

    HTML

    <Block flex style={imgContainer}>
       <Image source={item.src} style={imageStyles} />
    </Block>
    

    得到了确切的解决方案here

    【讨论】:

      【解决方案2】:

      目前不支持 require 中的动态路径。在包中引用图像的唯一允许方法是在源代码中逐字写入 require('name-of-the-asset')。

      您需要在您的 json 中添加对图像的要求。检查下面的示例

        const Profiles=[
            {
            "id" : "1",
            "name" : "Peter Parker",
            "src" : require('../images/user1.png'),
            "age":"70",
          },
          {
          "id" : "2",
          "name" : "Barack Obama",
          "src" : require('../images/user2.png'),
          "age":"19",
          },
          {
          "id" : "3",
          "name" : "Hilary Clinton",
          "src" : require('../images/user3.png'),
          "age":"50",
          }
      ]
      export default Profiles;
      

      【讨论】:

      • 我猜这是正确的,我猜蒂姆提供的不是一个可行的解决方案。
      • 我应该如何在 HTML 中呈现 src?使用
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-16
      • 2018-03-23
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-23
      相关资源
      最近更新 更多