javascript - 对图像文件 react native 使用变量

标签 javascript ios react-native

我知道要在 React Native 中使用静态图像,您需要专门对该图像执行要求,但我正在尝试根据数字加载随机图像。例如,我的目录中有 100 张名为 img1.png - img100.png 的图像。我正在尝试找出一种方法来执行以下操作

<Image source={require(`./img${Math.floor(Math.random() * 100)}.png`)}/>

我知道这不是故意的,但如果有任何变通办法,我们将不胜感激。

最佳答案

对于任何了解 react-native 野兽的人来说,这应该有所帮助:)

我过去也访问过几个网站,但发现它越来越令人沮丧。直到我读到 this site here .

这是一种不同的方法,但它最终会带来返回。 基本上,最好的方法是将所有资源加载到一个地方。 考虑以下结构

app  
   |--img
      |--image1.jpg
      |--image2.jpg
      |--profile
          |--profile.png
          |--comments.png
      |--index.js

index.js 中,您可以这样做:

const images = {
    profile: {
        profile: require('./profile/profile.png'),
        comments: require('./profile/comments.png'),
    },
    image1: require('./image1.jpg'),
    image2: require('./image2.jpg'),
};

export default images;

在您的 View 中,您必须像这样导入图像组件:

import Images from './img/index';

render() {
    <Image source={Images.profile.comments} />
}

每个人都有不同的手段,选择最适合自己的。

大满-问:这个答案怎么用变量?

好吧,因为 require 只接受文字字符串,所以你不能使用变量、连接字符串等。这是次要的事情。是的,这仍然是很多工作,但现在你可以做一些类似于 OP 问题的事情:

render() {
  var images = { test100: "image100" };
  return (
    <View>
      <Text>
       test {images["test" + "100"]}
      </Text>
    </View>
  );
}

关于javascript - 对图像文件 react native 使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33907218/

相关文章:

Javascript 数组变量作用域

javascript - 如何访问不同 Controller 的功能? - JavaScript MVC

ios - 如何更改以编程方式为 UIButton 添加的约束

ios - Cocos2d : GPU having to process the non visible CCSprite quads

ios - 在不影响其他 UITableViewCell 的情况下为 UITableViewCell 设置动画按钮

react-native - 错误 : ENOENT: no such file or directory, 打开 'android\app\src\main\assets\index.android.bundle'

javascript - 按顺序将项目添加到列表中

javascript - Jquery 移动幻灯片

javascript - React-native android 样式 textInput

javascript - React 中 React Native 的 FlatList 等价物