【问题标题】:Image not showing when mapping an array and render an image映射数组并渲染图像时未显示图像
【发布时间】:2019-01-27 00:01:25
【问题描述】:

我的项目中有这个图像数组。

this.state.destinations = [{
    "destinationId": "001",
    "img": "../../assets/img/destinations/001.png"
  },
  {
    "destinationId": "002",
    "img": "../../assets/img/destinations/002.png"
  },
  {
    "destinationId": "003",
    "img": "../../assets/img/destinations/003.png"
  }]
}

我试图在 Image 组件的视图中重复它们中的每一个,如下所示:

render() {

    var {navigate} = this.props.navigation;

    return (
        <LinearGradient 
          colors={['#514A9D', '#24C6DC']} start={[0.0, 0.5]} end={[1.0, 0.5]} locations={[0.0, 1.0]} style={{flex:1}}>
            <ScrollView>
              {
                <View style={{paddingTop: 24}}>
                  {
                    this.state.destinations.map(dest => {
                      return <Image style={{height: 200, width: 600}} key={dest.destinationId} source={require(dest.img)} resizeMode="contain" />
                    })
                  }
                </View>
              }
            </ScrollView>
        </LinearGradient>
    );
  }

但是当我尝试运行时,我的手机出现了一些疯狂的错误:

我试图在 expo 中运行应用程序,我只是在 react-native 模式下开发它,而不是 react-native-init 模式。

【问题讨论】:

    标签: react-native react-native-image


    【解决方案1】:

    尝试按以下方式重构您的代码,将您对 require 的使用直接移至定义数据的位置,以便正确评估静态资源路径:

    this.state.destinations = [{
        "destinationId": "001",
        "img": require("../../assets/img/destinations/001.png")
      },
      {
        "destinationId": "002",
        "img": require("../../assets/img/destinations/002.png")
      },
      {
        "destinationId": "003",
        "img": require("../../assets/img/destinations/003.png")
      }]
    }
    

    然后像这样更新您呈现&lt;Image /&gt; 的方式,删除对require() 的调用并直接引用dest.img

    this.state.destinations.map(dest => {
      return <Image source={dest.img}
               key={dest.destinationId}
               style={{height: 200, width: 600}} 
               resizeMode='contain' />
    })
    

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      动态图片导入:

      "img": require("../../assets/img/destinations/001.png")
      <Image source={dest.img} />
      

      博览链接:code

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-05
        • 2023-04-10
        • 2013-07-06
        • 2020-01-07
        • 2022-10-06
        相关资源
        最近更新 更多