映射数组和渲染图像时未显示图像

时间:2018-08-20 20:05:55

标签: react-native react-native-image

我的项目中有这一系列图像。

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组件的View中重复它们中的每一个:

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>
    );
  }

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

Error

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

2 个答案:

答案 0 :(得分:3)

尝试通过以下方式重构代码,将对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")
  }]
}

然后像这样更新渲染<Image />的方式,删除对require()的调用并直接引用dest.img

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

希望这会有所帮助!

答案 1 :(得分:2)

动态图像导入:

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

展览链接:code