繁体   English   中英

如何在 React 组件中导入图像 (.svg, .png)

[英]How to import image (.svg, .png ) in a React Component

我正在尝试在我的一个反应组件中导入一个图像文件。 我有 web 包的项目设置

这是我的组件代码

import Diamond from '../../assets/linux_logo.jpg';

 export class ItemCols extends Component {
    render(){
        return (
            <div>
                <section className="one-fourth" id="html">
                    <img src={Diamond} />
                </section>
            </div>
        )
    } 
}

这是我的项目结构。

在此处输入图像描述

我通过以下方式设置了我的 webpack.config.js 文件

{
    test: /\.(jpg|png|svg)$/,
    loader: 'url-loader',
    options: {
      limit: 25000,
    },
},
{
    test: /\.(jpg|png|svg)$/,
    loader: 'file-loader',
    options: {
      name: '[path][name].[hash].[ext]',
    },
},

附言。 我可以从任何其他远程来源获取图像,但不能从本地保存的图像。 JavaScript 控制台也没有给我任何错误。 请任何帮助。 我对反应很陌生,无法找到我做错了什么。

尝试使用

import mainLogo from'./logoWhite.png';

//then in the render function of Jsx insert the mainLogo variable

class NavBar extends Component {
  render() {
    return (
      <nav className="nav" style={nbStyle}>
        <div className="container">
          //right below here
          <img  src={mainLogo} style={nbStyle.logo} alt="fireSpot"/>
        </div>
      </nav>
    );
  }
}

您也可以使用 require 来渲染图像,例如

//then in the render function of Jsx insert the mainLogo variable

class NavBar extends Component {
  render() {
    return (
      <nav className="nav" style={nbStyle}>
        <div className="container">
          //right below here
          <img src={require('./logoWhite.png')} style={nbStyle.logo} alt="fireSpot"/>
        </div>
      </nav>
    );
  }
}

如果图像在 src/assets 文件夹中,您可以在 require 语句中使用require和正确的路径,

var Diamond = require('../../assets/linux_logo.jpg');

 export class ItemCols extends Component {
    render(){
        return (
            <div>
                <section className="one-fourth" id="html">
                    <img src={Diamond} />
                </section>
            </div>
        )
    } 
}

要使用变量动态导入图像,您可以使用以下命令:

  const imageName = "myImage.png"
  const images = require.context('../images',true);
  const [imgUrl, setImgUrl] = useState('');

  useEffect(() => {
    if (images && imageName) {
      setImgUrl(
        images(`./${imageName}`).default
      );
    }
  }, [imageName,images]);

  ...

  <img src={imgUrl} />

创建一个文件夹并将其命名为images.tsimages.js在您的资产文件夹中或您想要的任何地方。

使用export {default as imageName} from 'route'语句导出文件夹中的所有图像。

export { default as image1 } from "assets/images/1.png";
export { default as image2 } from "assets/images/2.png";
export { default as image3 } from "assets/images/3.png";
export { default as image4 } from "assets/images/4.png";

然后使用import {imageDefaultName} from 'route'导入图像

import {image1,image2,image3,image4} from 'assets/images'

<img src={image1} />
<img src={image2} />
<img src={image3} />
<img src={image4} />

或者

import * as images from 'assets/images'

<img src={images.image1} />
<img src={images.image2} />
<img src={images.image3} />
<img src={images.image4} />
import React, {Component} from 'react';
import imagename from './imagename.png'; //image is in the current folder where the App.js exits


class App extends React. Component{
    constructor(props){
     super(props)
     this.state={
      imagesrc=imagename // as it is imported
     }
   }

   render(){
       return (

        <ImageClass 
        src={this.state.imagesrc}
        />
       );
   }
}

class ImageClass extends React.Component{
    render(){
        return (

            <img src={this.props.src} height='200px' width='100px' />
        );
    }
}

export default App;

我也有类似的要求,需要导入 .png 图像。 我已将这些图像存储在公共文件夹中。 所以以下方法对我有用。

<img src={process.env.PUBLIC_URL + './Images/image1.png'} alt="Image1"></img> 

除了上述之外,我还尝试使用 require ,它也对我有用。 我已将图像包含在 src 目录的 Images 文件夹中。

<img src={require('./Images/image1.png')}  alt="Image1"/>

你也可以试试:

...
var imageName = require('relative_path_of_image_from_component_file');
...
...

class XYZ extends Component {
    render(){
        return(
            ...
            <img src={imageName.default} alt="something"/>
            ...
        )
    }
}
...

注意:确保 Image 不在项目根文件夹之外。

如果我们不使用“create-react-app”,步骤很少,(webpack@5.23.0) 首先我们应该将file-loader安装为devDedepencie,下一步是在webpack.config中添加规则

 { test: /\\.(png|jpe?g|gif)$/i, loader: 'file-loader', }

,然后在我们的 src 目录中,我们应该创建名为 declarationFiles.d.ts 的文件(例如)并在其中注册模块

 declare module '*.jpg'; declare module '*.png';

,然后重新启动开发服务器。 在这些步骤之后,我们可以像下面的代码一样导入和使用图像

 import React from 'react'; import image from './img1.png'; import './helloWorld.scss'; const HelloWorld = () => ( <> <h1 className="main">React TypeScript Starter</h1> <img src={image} alt="some example image" /> </> ); export default HelloWorld;

适用于打字稿和 javacript,只需将扩展名从 .ts 更改为 .js

干杯。

我用user5660307回答。 对于使用 react 和 nodejs 的服务器端渲染,您可以在 express 服务器中添加:

app.use(express.static("public"));

在 webpack.client.js 中:

module.exports = {
  entry: "./src/client/client.js",

  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, "public"),
  },

  module: {
    rules: [
      ...
      {
        loader: require.resolve("file-loader"),
        exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
        options: {
          name: "static/media/[name].[hash:8].[ext]",
        },
      },
      {
        test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
        loader: require.resolve("url-loader"),
        options: {
          name: "static/media/[name].[hash:8].[ext]",
        },
      },
    ],
  },
};

简单的方法是使用 location.origin
它将返回您的域
前任
http://本地主机:8000
https://yourdomain.com

然后用一些字符串连接...
享受...

<img src={ location.origin+"/images/robot.svg"} alt="robot"/>

更多图片?

var images =[
"img1.jpg",
"img2.png",
"img3.jpg",
]

images.map( (image,index) => (

  <img key={index} 
       src={ location.origin+"/images/"+image} 
       alt="robot"
  />
) )

解决了在 src 文件夹中移动带有图像的文件夹时的问题。 然后我转向图像(通过“create-react-app”创建的项目)
let image = document.createElement("img"); image.src = require('../assets/police.png');

暂无
暂无

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

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