Display an image from url in ReactJS

六眼飞鱼酱① 提交于 2021-02-07 04:44:20

问题


I want to display an image from a URL in React. For example, I want this image

https://images.pexels.com/photos/20787/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=350

to be displayed in a Card body or reactJS. Is it possible to do it or do I have to download it to assets before I can display it? And how to do it?


回答1:


As you do in HTML

 import React from "react";
 import ReactDOM from "react-dom";

 function App() {
   return (
     <img 
      src="https://images.pexels.com/photos/20787/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=350"
      alt="new"
      />
   );
 }

 const rootElement = document.getElementById("root");
 ReactDOM.render(<App />, rootElement);



回答2:


You can use tag for displaying the image.If the image source is in props/state use <img src={this.props.url}/>




回答3:


Yes. it is possible. just use <img /> tag.

<img src="https://images.pexels.com/photos/20787/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=350">



回答4:


In the App.js file, write following code:

import React from 'react';

function App() {

  return(
    <div>
      <img src="image-url" alt="image" />
    </div>
  );
}

export default App;



回答5:


To solve this;

For local images:

Use an import statement No need to pollute the public folder

import slideImg1 from '../../assets/pexels-pixabay-259915.jpg';

The use in Jsx like this

    const solveLocalImg = () => (
<img src={slideImg1}/>

//or

<div data-src={slideImg1}>
      </div>
)

For online images

Use an array

let imgs = [
  'https://res.cloudinary.com/stealthman22/image/upload/v1586308024/new-portfolio/hero/time-lapse-photography-of-waterfalls-during-sunset-210186.jpg',
  'https://res.cloudinary.com/stealthman22/image/upload/v1586308023/new-portfolio/hero/two-cargo-ships-sailing-near-city-2144905.jpg',
];

 const solveOnlineImg = () => (
<div>
<img src={imgs[0]}/>
<img src={imgs[1]}/>
</div>
)

You can use as many images as you like with the second method. It even makes it easy for you to manage your images. Hopefully, soon enough we'd either get a solution that can make us do things how we are used to with just HTML CSS and js

For now, we are stuck with amazing Webpack



来源:https://stackoverflow.com/questions/51184136/display-an-image-from-url-in-reactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!