【问题标题】:How to import image (.svg, .png ) in a React Component如何在 React 组件中导入图像(.svg、.png)
【发布时间】:2017-10-05 00:26:22
【问题描述】:

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

这是我的组件代码

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]',
    },
},

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

【问题讨论】:

  • Shadid,你试过 吗?
  • 是的,我试过了。控制台再次没有错误,但我看不到图像
  • 你应该做一个 webpack 构建并检查图像的存储位置。在 img src 中使用该路径。
  • @vijayst 保佑你好先生.. 那行得通。 :)

标签: javascript reactjs webpack


【解决方案1】:

尝试使用

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

【讨论】:

  • 如果我要导入 10 张图片会怎样?
  • @LeoGasparrini - 我不确定我是否明白你在问什么 - 只要你在导入时给它们唯一的名称,你应该能够导入任意数量的,不是吗?
  • 我正在尝试相同的方法,但 babel 抱怨说它无法理解 png 文件是什么。如何让 babel 从转译中跳过 png 文件?
  • 我建议您使用创建反应应用程序。此类问题已通过设置预先解决。而且您不需要重新设计流程
  • 对于好奇的人来说,当我们导入这样的图像时,mainLogo 实际上是一个数据 URI (data:image/png;....) 或一个公共 URL (/static/ logoWhite.svg) 这取决于你的捆绑器。
【解决方案2】:

你也可以使用 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>
    );
  }
}

【讨论】:

  • 当我尝试这个解决方案时,我得到了这个错误[HMR] unexpected require(./src/components/LeftBar/home.svg) from disposed module ./src/components/LeftBar/LeftBar.js LeftBar App@http://localhost:3000/static/js/main.chunk.js:115:79你知道发生了什么吗?谢谢
【解决方案3】:

如果图像位于 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>
        )
    } 
}

【讨论】:

    【解决方案4】:

    如果我们不使用“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;

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

    干杯。

    【讨论】:

      【解决方案5】:

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

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

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

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

      【讨论】:

        【解决方案6】:

        你也可以试试:

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

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

        【讨论】:

          【解决方案7】:

          要使用变量动态导入图像,可以使用以下方法:

            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} />
          

          【讨论】:

            【解决方案8】:
            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;
            

            【讨论】:

              【解决方案9】:

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

              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]",
                      },
                    },
                  ],
                },
              };
              

              【讨论】:

                【解决方案10】:

                简单的方法是使用 location.origin
                它将返回您的域
                前任
                http://localhost: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"
                  />
                ) )
                

                【讨论】:

                  【解决方案11】:

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

                  【讨论】:

                  • 可能是这样:import React, { Component } from 'react'; export default class Lesson3 extends Component { render() { return ( ); } }
                  猜你喜欢
                  • 2020-12-17
                  • 1970-01-01
                  • 2016-03-11
                  • 2020-07-31
                  • 2021-02-07
                  • 2018-02-06
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多