Load local images in React.js

后端 未结 10 2050
隐瞒了意图╮
隐瞒了意图╮ 2020-11-30 23:08

I have installed React using create-react-app. It installed fine, but I am trying to load an image in one of my components (Header.js, file path: <

相关标签:
10条回答
  • 2020-11-30 23:39

    Instead of use img src="", try to create a div and set background-image as the image you want.

    Right now it's working for me.

    example:

    App.js

    import React, { Component } from 'react';
    import './App.css';
    
    
    
    class App extends Component {
    
      render() {
        return (
          <div>
            <div className="myImage"> </div>
          </div>
        );
      }
    }
    
    export default App;
    

    App.css

    .myImage {
      width: 60px;
      height: 60px;
      background-image: url("./icons/add-circle.png");
      background-repeat: no-repeat;
      background-size: 100%;
    }
    
    0 讨论(0)
  • 2020-11-30 23:39

    In React.js latest version v17.0.1, we can not require the local image we have to import it. like we use to do before = require('../../src/Assets/images/fruits.png'); Now we have to import it like = import fruits from '../../src/Assets/images/fruits.png';

    Before React V17.0.1 we can use require(../) and it is working fine.

    0 讨论(0)
  • 2020-11-30 23:42

    You have diferent ways to achieve this, here is an example:

    import myimage from './...' // wherever is it.
    

    in your img tag just put this into src:

    <img src={myimage}...>
    

    You can also check official docs here: https://facebook.github.io/react-native/docs/image.html

    0 讨论(0)
  • 2020-11-30 23:44

    If you want load image with a local relative URL as you are doing. React project has a default public folder. You should put your images folder inside. It will work.

    0 讨论(0)
提交回复
热议问题