映射时显示对象数组中的图像失败
我正在学习 ReactJS,我正试图从对象数组中显示社交列表,就像这样:
const baseUrl = "./";
export const SocialData = [
{
platform: "Linkedin",
link: "https://www.linkedin.com/in//",
icon: baseUrl + "linkedin.png",
},
{
platform: "Github",
link: "https://github.com/",
icon: baseUrl + "github.png",
},
];
然后在我的组件中,我会像这样显示它:
import { SocialData } from "../../data/social";
import "./socials.css";
function Socials() {
const data = SocialData;
return <div className="social-contact">
{/* <img src={require('./linkedin.png')}/>
*/} {
data.map((item) => {
return (
<a href={item.link} key={item.platform}>
<div className="social-icon-div">
<img src={ require(item.icon) } className="social-icon" />
</div>
</a>
)
})}
</div>;
}
注释的图像工作正常,但是当我尝试在我的地图中执行相同操作时,它会显示并抛出此错误:
Uncaught Error: Cannot find module './linkedin.png' at webpackEmptyContext (socials|sync:2:1) at Socials.js:14:1 at Array.map () at Socials (Socials.js:7:1) at renderWithHooks (react-dom.development.js:14985:1) at mountIndeterminateComponent (react-dom.development.js:17811:1) at beginWork (react-dom.development.js:19049:1) at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1) at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1) at invokeGuardedCallback (react-dom.development.js:4056:1)
我试图将要求直接放入数据中,它也会这样做。 我也试过
<img src={require( "" + props.src )} alt={props.imageAlt} />
正如 这里 所述,但没有任何效果。 谢谢你的帮助!
我来晚了,但我刚刚遇到了同样的问题,我想到的唯一解决方法是保存图像,然后将其导入为变量,然后将该变量用作 Link 属性值的模板文字。
For example:
import linkedinImg from "./img/linkedIn.png"
import githubPng from "./img/github.png"
export const SocialData = [
{
platform: "Linkedin",
link: "https://www.linkedin.com/in//",
icon: `${linkedinImg}`,
},
{
platform: "Github",
link: "https://github.com/",
icon: `${githubImg}`,
},
];
然后当您在
<a href={item.link} key={item.platform}>
中使用它时,它就会起作用,缺点是我将图像下载到我的电脑上,但我无论如何都会这样做。希望这对以后的任何人都有帮助。