简体   繁体   中英

Image Source (src) when passed to Reusable-Component does not show image in UI

I have added an image in the public folder of React-Project. Now, when I want to show an image - it gets showed up in a component, but if I try to pass its url and show the image in some reusable component - I find that image is not shown in UI.

Can someone help me out?

Home.js

import React, { Component } from 'react';
import Cards from './cards';

class Home1 extends Component {

  render(){
    return(
      <div>
        <img src="img/aishwarya.jpg" />
        <Cards title="Aishwarya" sourcelink="img/aishwarya.png" details="Miss World 1994" />
      </div>
    )
  }

}

export default Home1;

Cards.js

import React from 'react';
import './cards.css';

const Cards = (props) => {

  return (
    <div className="cardHolder">
      <div className="imageHolder">
        <img src={props.sourcelink} />
      </div>
      <div className="contentHolder">
        <h3>{props.title}</h3>
        <p>{props.details}</p>
      </div>
    </div>
  );

}

export default Cards;

Output:

在此处输入图像描述

When using webpack , for images under src , a path like img/aishwarya.jpg is only available during build time .

You need to import it, see Adding Images, Fonts, and Files :

import image from "./img/aishwarya.jpg";
console.log(image) // /aishwarya.84287d09.jpg

<img src={image} />
<img src={require("img/aishwarya.jpg")} />

See working example:

编辑interesting-smoke-zv0pv

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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