无法在本机中加载图像

时间:2018-10-11 06:11:18

标签: javascript reactjs react-native

我被困在以本机模式加载图像。我经历了类似问题中给出的所有解决方案,但答案对我而言没有帮助。我尝试导入图像,就像我们在使用import或require这样的反应时所做的一样,但是这两个选项都无法正常工作。

供您参考的PFB代码

import React, { Component } from 'react';
import { Card, CardTitle, CardContent, CardAction, CardButton, CardImage } from 'react-native-material-cards';
import aboutImage from "https://images.pexels.com/photos/34950/pexels-photo.jpg";
import {
  Button,
  View,
  Text,
  ScrollView, StyleSheet
} from 'react-native'

class About extends Component {

  handleScroll = e => {

  }

  render() {
    return (
      <ScrollView onScroll={this.handleScroll}>
        <View style={styles.container}>
          <Text style={styles.text}>Who we are</Text>
          <Card style={{backgroundColor: "#fff", boxShadow: "2px 3px #3333"}}>
            <CardImage 
              source={{uri:aboutImage }}
              title="About US"
            />
            <CardContent text="Testing" />
          </Card>
      </View>
    </ScrollView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    margin: 20
  },
  text:{
    color: "#06357a",
    fontWeight: "bold",
    fontSize: 30,
    fontFamily: "FreeSans,Arimo,Droid Sans,Helvetica,Arial,sans-serif"
  },
  text1:{
    color: "#06357a",
    fontWeight: "bold",
    fontFamily: "FreeSans,Arimo,Droid Sans,Helvetica,Arial,sans-serif"
  }
});

export default About;

.babelrc

{
  "presets": ["module:metro-react-native-babel-preset"]
}

编辑

我尝试将图像下载到本地,并使用require导入它们,但出现错误

  

错误:捆绑失败:错误:无法解析模块   ../../../../assets/AboutUS.jpg来自   D:\react-native\AppUsingRN\components\Layout\components\About.js:   在以下位置找不到模块../../../../assets/AboutUS.jpg   D:\react-native\AppUsingRN\components\Layout\components\About.js。   实际上,这些文件都不存在:

我喜欢导入

   <CardImage 
          source={{uri: require('../../../../assets/AboutUS.jpg')}} 
          title="About US"
        />

我无法找出问题所在。

2 个答案:

答案 0 :(得分:1)

它应与:

<CardImage 
  source={{ uri: "https://images.pexels.com/photos/34950/pexels-photo.jpg" }}
  title="About US"
/>

答案 1 :(得分:1)

如果使用require

const imageByRequire = require('../../../../assets/AboutUS.jpg');
<CardImage
  source={imageByRequire}
  title={'About US'}
/>

如果直接使用uri

const imageByUri = "https://images.pexels.com/photos/34950/pexels-photo.jpg";
<CardImage
  source={imageByUri}
  title={'About US'}
/>

如果“它以某种方式无法正常工作”,可能是下载或下载错误(什么都没有),也许您可​​以加上defaultSource

const imageByUri = "https://images.pexels.com/photos/34950/pexels-photo.jpg";
const defaultImage = require('../../../../assets/AboutUS.jpg');
<CardImage
  defaultSource={defaultImage}
  source={imageByUri}
  title={'About US'}
/>

希望有帮助:)