react-native - 用 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 Native 中,所有正在导入的文件都捆绑在一起。metro 捆绑器需要知道将在编译时使用的所有文件
实现这种情况的解决方法,例如
const possiblePaths = {
'one': require('path/to/file/1),
'two': require('path/to/file/2)
}
funtion(type){
return possiblePaths[type]
}
推荐阅读
- qt - 如何在两个 ListView 之间共享 ItemSelectionModel
- .htaccess - .htaccess 在一次 301 重定向中将所有“+”转换为“-”
- asp.net - 如何正确地将目标框架更改为 .NET 4.0
- ios - 未找到架构 x86_64 的 MDF 国际化框架
- php - explode() 期望参数 2 是字符串,给定数组
- c - 寄存器如何作为汇编中的参数工作?
- java - 如果我在一个请求中获得四个 pojo,如何重新编写代码以进行改造?
- if-statement - Sumif 和 IF,将一列相加并将其与另一列进行比较
- c# - 运行两个任务时出现内存不足异常 (Outlook VSTO)
- real-time - 使用 RT 补丁在 linux 中为 ktimersoftd 设置默认优先级