【问题标题】:React Native SectionList Images from JSON来自 JSON 的反应本机 SectionList 图像
【发布时间】:2021-07-01 16:34:50
【问题描述】:

我在将图像从 JSON 文件渲染到部分列表时遇到了一些问题,即使我对文本数据没有任何问题。

这是我的 JSON 数据:

   {
      "title" : "Friday",
      "data": 
      [
         {
            "artist": "artist 1",
            "stage": "The Oak",
            "Instagram": "insta",
            "Spotify": "spot",
            "date": "10/8/2021",
            "Image": "../assets/art1.jpg",
            "Time" : "4:30PM - 5:00 PM"
         },
         {
            "artist": "artist 2",
            "stage": "The Oak",
            "Instagram": "insta",
            "Spotify": "spot",
            "date": "10/8/2021",
            "Image": "../assets/art2.jpg",
            "Time" : "5.00PM - 5:30 PM"

         }
         
      ]},

我知道您必须使用 require 函数来渲染它,但我似乎无法正确处理它。

这里是章节列表:

 <SectionList
      sections={data}
      keyExtractor={(item, index) => index.toString()}
      renderItem={({ item }) => (<View style={styles.listItemView}>
        <Image style={styles.image} source={require(item.Image)} />

        <View>
          <Text style={styles.listItem}>{item.artist}</Text>
          <Text style={styles.listItemTime} >{item.Time}</Text>
        </View>
      </View>)}
      renderSectionHeader={({ section }) => (
        <View style={styles.item}>
          <Text style={styles.title}>{section.title}</Text>
        </View>)}
    />

欢迎任何帮助。如果我需要添加附加信息,请告诉我!

谢谢!

【问题讨论】:

  • 动态导入是一种反模式。您不应动态导入图像。即使你成功地使它工作,图像仍然不会被复制到 bundle 中,因为 react native 会认为这些图像没有被使用。 github.com/benmosher/eslint-plugin-import/blob/v2.22.1/docs/…
  • 谢谢@UğurEren 有没有办法正确实现这个效果?
  • 没有对每个图像进行硬编码

标签: javascript react-native react-native-flatlist react-native-sectionlist


【解决方案1】:

您可以使用 if-else 或 switch 语句来获取您要使用的图像。

const getArtImage = (artName) => {
  switch (artName){
    case 'art1':
      return require('../assets/art1.jpg');

    case 'art2':
      return require('../assets/art2.jpg');

    default:
      return require('../assets/defaultArt.jpg');
  }
}

并在您的 Image 组件中使用此 getArtImage 函数。

<Image style={styles.image} source={getArtImage(item.Image)} />

item.Image 应该类似于 art1art2 等。

--

如果你的json是本地文件,可以转成js文件。

export default {
  title: "Friday",
  data: [
    {
      artist: "artist 1",
      stage: "The Oak",
      Instagram: "insta",
      Spotify: "spot",
      date: "10/8/2021",
      Image: require("../assets/art1.jpg"),
      Time: "4:30PM - 5:00 PM",
    },
    {
      artist: "artist 2",
      stage: "The Oak",
      Instagram: "insta",
      Spotify: "spot",
      date: "10/8/2021",
      Image: require("../assets/art2.jpg"),
      Time: "5.00PM - 5:30 PM",
    },
  ],
};

【讨论】:

  • 谢谢分享!当图像超过 50 张时,switch 语句是最好的方法吗?
  • 很遗憾,是的
  • 非常感谢您的帮助:)
猜你喜欢
  • 2022-01-02
  • 2020-05-04
  • 2021-04-15
  • 1970-01-01
  • 1970-01-01
  • 2021-05-24
  • 2021-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多