React Native - 动态图像源

新手上路,请多包涵

我正在尝试使用 map 方法遍历 SOURCE 数组,但我不断收到此错误:

Unknown named module: '../images/one.jpeg'

有人知道为什么会这样吗? require 中的文件路径肯定是正确的。

 var SECTIONS = [
  {
    title: 'One',
    fileName: 'one.jpeg',
  },
  {
    title: 'Two',
    fileName: 'two.jpeg',
  },
  {
    title: 'Three',
    fileName: 'three.jpeg',
  },
  {
    title: 'Four',
    fileName: 'four.jpeg',
  },
];

{SECTIONS.map((section, i) => (
   <CategoryCard
     key={i}
     source={require(`../images/${section.fileName}`)}
     title={section.title}
   />
))}

原文由 AHinson 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 392
2 个回答

我认为这是不可能的,因为 React Native 需要提前知道要捆绑什么(AFAIK)。但是,您可以 require 数组中的所有文件:

 var SECTIONS = [
  {
    title: 'One',
    file: require('../images/one.jpeg'),
  },
  {
    title: 'Two',
    file: require('../images/two.jpeg'),
  },
  {
    title: 'Three',
    file: require('../images/three.jpeg'),
  },
  {
    title: 'Four',
    file: require('../images/four.jpeg'),
  },
];

{SECTIONS.map((section, i) => (
   <CategoryCard
     key={i}
     source={section.file}
     title={section.title}
   />
))}

原文由 Davin Tryon 发布,翻译遵循 CC BY-SA 3.0 许可协议

您不能使用动态链接。我发现解决这个问题的最好方法是:

 var SECTIONS = {
  One: {
    title: 'One',
    file: require('../images/one.jpeg'),
  },
  Two: {
    title: 'Two',
    file: require('../images/two.jpeg'),
  },
  Three: {
    title: 'Three',
    file: require('../images/three.jpeg'),
  },
  Four: {
    title: 'Four',
    file: require('../images/four.jpeg'),
  },
};

{SECTIONS.map((section, i) => (
   <CategoryCard
     key={i}
     source={section.file}
     title={section.title}
   />
))}

这样,你就可以只使用这些文件,如果你有某种动态图像选择,你可以只使用这样的东西

<Image source={SECTIONS[image.type]} />

原文由 Truca 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏