React Native需要从JSON文件中获取图片

问题描述 投票:0回答:1

我想用一种更动态的方式来显示文章。我做了一个JSON文件,其中包含了所有的信息,并在上面循环,为每个项目在主页上创建一个项目。这是在工作,标题和文本显示。现在我在图片方面遇到了问题。我没有得到任何错误,所以我想我可能与json文件中调用的路径有关。

项目结构。

src
--articles
----img
------img.jpg
----articlePreview.js
----articles.json
----fullArticle.js
--homepage
----index.js 
App.js

测试json,正如你所看到的,我尝试了一些不同的路径,也尝试了一些更多的路径。

{
    "articles": [
        {
            "title": "Test",
            "imageName": "/img/img.jpg",
            "text": "more text to test"
        },
        {
            "title": "Test22",
            "imageName": "./img/img.jpg",
            "text": "more text to test"
        }
    ]
}

在主页上,我把json文件中的所有项目映射成这样:

  const contents = json.articles.map(function (item) {
    return (
      <ArticleHome title={item.title} text={item.text} image={item.imageName} />
    );
 });

最后是应该显示它们的组件。

function ArticleHome({title, text, imageName}) {

  return (
    <View>
      <Card>
        <CardItem header bordered>
          <Body>
            <Image
              style={{ width: '100%', height: 400 }}
              source={{uri: imageName}} 
            />
            <Text>
              {title}
            </Text>
            <Text>
              {text.substring(0,240)}...
            </Text>
            <Button
              title="Lees Meer"
              color="#d10a10"
              onPress={() => RootNavigation.navigate('Article')}
            />
          </Body>
        </CardItem>

      </Card>
    </View>
  );
}
react-native react-native-android
1个回答
1
投票

而不是以这种方式传递图像

"imageName": "/img/img.jpg",

你必须得到一个像下面这样的图片。

imageName: require("./img/img.jpg"),

然后简单地将这个路径传递给你的 Image 标签

<Image source={imageName} />

下面是一个示范小吃。

https:/snack.expo.io@waheed25微笑的胡萝卜。

编辑:这里是一个带有你的代码的演示

https:/snack.expo.io@waheed25c91df6。

© www.soinside.com 2019 - 2024. All rights reserved.