【问题标题】:React Native : Alternate way to get the Image require to work when array of image paths got dynamically from fetchapiReact Native:当图像路径数组从 fetchapi 动态获取时,获取图像需要工作的替代方法
【发布时间】:2020-03-10 19:37:04
【问题描述】:

React Native:当图像路径数组从 fetchapi 动态获取时,获取图像的替代方法需要工作

尝试了以下方法并意识到 require 总是需要引号('')中的固定路径,这在已知静态图像路径时效果很好。你应该是映射从 fetchapi 接收到的图像的替代方法。

source={require('./assets/images/'+{item.image_path})} 
Example fetch api json response is: [{user_name: 'DynamicUser1', image_path: 'DynamicUser1.jpg'},{user_name: 'TestUser1', image_path: 'TestUser1.jpg'}... ]

需要其他方法来获取使用从 fetch api 正确选择的动态图像路径渲染的图像。

userData = this.state.resultsUserData.map((item) => {

    return (
              <View key={item.user_name} style={ styles.container }>
                <Text style={styles.title}>
                  {item.user_name}
                </Text> 

        <TouchableOpacity goBack={()=>this.backAction} onPress={()=>this.homepage()}>
                  <Image key={item.image_path} 
                    source={require('./assets/images/'+{item.image_path})}
                </TouchableOpacity> 
        </View>
  )
}

【问题讨论】:

    标签: react-native


    【解决方案1】:

    require 不能像那样动态工作。由于您已经在资产中拥有图像,因此您应该提前为每个图像编写require,并在需要时调用适当的图像。您可以阅读有关此限制的更多信息here

    【讨论】:

    • 谢谢。我看着它,但无法获得克服这个静态路径问题所需的方法。我在 assets/images 文件夹中有带有文件名的图像。我的 fetchapi 调用将根据我的查询获得一个带有文件名的 json 对象数组,如下所示:[{user_name: 'DynamicUser1', image_path: 'DynamicUser1.jpg'},{user_name: 'TestUser1', image_path: 'TestUser1.jpg '}...]。需要知道如何做同样的事情。我已经把上面的代码和这个地图函数放在了一起:userData = this.state.resultsUserData.map((item)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-20
    • 2021-06-13
    相关资源
    最近更新 更多