在 react.js 中加载图像失败
2022-09-30
231
我试图将图像添加到 React 项目。我使用
import image from "./ImageSource"
当我导入本地图像(如
import image from "./path/to/image.jpg";
...
return <img src={image} />
)时,它显示成功。
但是当我尝试使用链接(如“https://picsum.photos/id/0/500”)导入图像时,它不起作用并出现错误:
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "image/jpeg". Strict MIME type checking is enforced for module scripts per HTML spec.
__________________________________
Uncaught (in promise) TypeError: Failed to fetch dynamically imported module: https://i.picsum.photos/id/0/1000/1000.jpg?hmac=2UP1ceqLjSmxh6sZh1wmL6yWx3nIMPvw2_b0ugpOv1o
这是我的代码:
import React from 'react'
import { useParams } from 'react-router-dom'
import image from "https://picsum.photos/id/0/500";
function Image() {
const {width, height} = useParams()
return (
<section className="container p-y-3">
<h1 className="clr-primary">Create Image</h1>
<h2>{width}</h2>
<h2>{height}</h2>
{/* The problem here */}
<img src={image} alt="" />
<img src={require("https://picsum.photos/id/0/500")} />
</section>
);
}
export default Image
如何从链接导入图像?
1个回答
我找到了解决方案。
渲染远程图像时,无需导入它(正如@Andy在评论中提到的)。它可以直接放入
src
prop 中
<img src="https://picsum.photos/id/10/1000"
Ahmed Abdelbaset
2022-09-30