简体   繁体   English

React Native - 无法从路径导入图像

[英]React Native - cannot import image from path

I have the following basic react native code:我有以下基本的反应本机代码:

在此处输入图像描述

import React from 'react';
import {StyleSheet, View, Image} from 'react-native';

//images
import login_blueGirl from './assets/images/login_blueGirl.png';


const App = () => {
  return (
    <>
     <View style={styles.container}>
        <Image source={login_blueGirl}></Image>
     </View>
    </>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column'
  }
});

export default App;

I'm getting a Cannot find module './assets/images/login_blueGirl.png' .我得到一个Cannot find module './assets/images/login_blueGirl.png' When I type ./ VSCode give me however the autocomplete option:当我输入./ VSCode 时,给我自动完成选项:

在此处输入图像描述 在此处输入图像描述

Any clue on why this is happening?关于为什么会发生这种情况的任何线索?

That's not quite how you're supposed to be importing images, use require instead.这不是您应该导入图像的方式,而是使用require

const App = () => {
    return (
        <View style={styles.container}>
            <Image source={require("./assets/images/login_blueGirl.png")} />
        </View>
    );
};

To import a static file like a .png file, you can declare要像.png文件一样导入 static 文件,您可以声明

const blueGirl = require("assets/images/login_blueGirl.png");

Then you can use it in an Image component然后你可以在Image组件中使用它

<Image style={styles.image} source={blueGirl} />

Also the image is used as a self closing tag you don't have to add another </Image> tag.此外,图像用作自结束标记,您不必添加另一个</Image>标记。

In order to fully understand how tags and syntax work always check out the official documentation React Native API为了充分理解标签和语法的工作原理,请查看官方文档React Native API

You can specify the width and height of the image to display it, do this:您可以指定要显示的图像的宽度和高度,执行以下操作:

const App = () => {
  return (
    <View style={styles.container}>
      <Image style={{ width: 100, height: 80 }} source={require("./assets/images/login_blueGirl.png")}></Image>
    </View>
  );
};

or或者

const styles = StyleSheet.create({
    imgStyle: {
        width: 50,
        height: 50,
    }
});

const App = () => {
    return (
        <View style={styles.container}>
            <Image style={styles.imgStyle} source={require("./assets/images/login_blueGirl.png")}></Image>
        </View>
    );
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM