Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

javascript - Unable to load images from local library in React.js

I have written a code for my website and unfortunately, i am not able to load images that are located in my local library. I have moved my images folder inside 'src' folder, but the image doesn't load at all.

Here is the code for my component called 'Landscape' which I am trying to load.

Code:

import React, {Component} from 'react';
import {Grid, Button, Row, Col, Thumbnail} from 'react-bootstrap';
import 'react-bootstrap-carousel';
import './Landscape.css';

export default class Landscape extends Component{
render(){
return(
<div className="thumbnails">
  <Grid>
    <Row>
      <Col xs={6} md={4}>
        <Thumbnail src=".Pictures/1.jpg" alt="242x240">
        <h3>Elephant</h3>
        <p>zoo</p>
        <p>
          <Button bsStyle="primary">Like</Button>
          {' '}
          <Button bsStyle="primary">Dislike</Button>
        </p>
        </Thumbnail>
      </Col>
    </Row>
  </Grid>
</div>

);
}}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you have a few images you can just import it directly in your component

import logo from './Pictures/1.jpg';

Then call it

<img src={logo} alt="logo" width={"240"} height={"240"}  />

if you have hundreds of images because you can’t use import paths, you have to create a images folder in the public folder and use this code.

 //This is the regular way.

  <img src={process.env.PUBLIC_URL + 'images/profile.svg'} width={"200"} height={"200"} className="profile-img" alt="profile" />

Another way you can specify each component has a images.js file, then import all the images that retarded of that component in images.js and name it as the related component name

images.js

import logo from './images/logo.svg';
import cover from './images/cover.svg';
import profile from './images/profile.svg';
import background1 from './images/body.svg';
export default {
    logo,
    cover,
    profile,
    background1
}

Then in your component you can just import images.js file:

import images from './images';

Then call any img you want:

      <img src={images.logo} className="App-logo" alt="logo" />
      <img src={images.cover} className="App-logo" alt="logo" />
      <img src={images.profile} className="App-logo" alt="logo" />
      <img src={images.background1} className="App-logo" alt="logo" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...