首页 > 解决方案 > 用 Expo 反应原生随机 BackImage

问题描述

我正在尝试使用 expo 将随机背景图像设置为 React Native。这是代码:

const randomNumber = Math.floor(Math.random() * 53) + 1;
const backimage = `./assets/b${randomNumber}.jpg`;

export default function App() {

  return (
    <SafeAreaView style={styles.container}>
      <ImageBackground source={require(backimage)} style={styles.image}>
       <Text>Hello World</Text>
      </ImageBackground>
    </SafeAreaView>
  );
}

我在codepen上尝试了randomNumber和backimage,它按预期工作,但没有反应原生。

我还尝试对 backimage = 进行硬编码./assets/b1.jpg,它也运行良好,但当我使用它时却不行: const backimage = ./assets/b${randomNumber}.jpg;

我不确定 expo 是否支持字符串插值。非常感谢并非常感谢。再次感谢。

标签: react-nativeexpo

解决方案


在 React Native 中,所有正在导入的文件都捆绑在一起。metro 捆绑器需要知道将在编译时使用的所有文件

实现这种情况的解决方法,例如

   const possiblePaths = {
     'one': require('path/to/file/1),
     'two': require('path/to/file/2)
    }

   funtion(type){
    return possiblePaths[type]
   }

推荐阅读