gpt4 book ai didi

react-native - 在 React 中使用 时调用本地资源

转载 作者:行者123 更新时间:2023-12-02 20:02:18 24 4
gpt4 key购买 nike

我正在尝试使用 ScrollView 显示图像。

我有一个代码,当我使用互联网上的图像时可以工作,但当它们是本地镜像时则不行。你能告诉我如何更正我的代码吗?

我知道错误来自于此:source={{require(image)}}但不知道如何正确编写

const images = [
'./images/localImage1.jpg',
'./images/localImage2.jpg',
//'https://someURLlink2.jpg',
//'https://someURLlink2.jpg',
]

render() {
let imageArray = []
let barArray = []
images.forEach((image, i) => {
console.log(image, i)
const thisImage = (
<Image
key={`image${i}`}
//source={{uri: image}}
source={{require(image)}}
style={{ width: deviceWidth }}
/>
)
imageArray.push(thisImage)

最佳答案

正如react-native所说

In order for this to work, the image name in require has to be known statically.

了解更多信息https://facebook.github.io/react-native/docs/images.html

因此解决方案将在数组中存储已经需要的图像

const images = [
require('./images/localImage1.jpg'),
require('./images/localImage2.jpg')
]

然后调用图像,如下所示;

render(){
let imageArray = []
let barArray = []
images.forEach((image, i) => {
console.warn(image, i)
const thisImage = (
<Image
key={`image${i}`}

source={image}
style={{ width: deviceWidth }}
/>
)
imageArray.push(thisImage)
})
return imageArray;
}

关于react-native - 在 React 中使用 <Image> 时调用本地资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55570831/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com