【发布时间】:2021-07-01 12:02:57
【问题描述】:
我正在尝试通过 const 对象动态加载 SVG,以便在其他块中轻松重用。 但 SVG 不显示。
当我在顶部导入 svg 并将其加载到 <Img src='../../images/svg-1.svg' /> 时,它可以正常工作,但我想动态导入它以重用它并在其他块中轻松更改 svg。
请检查以下代码:
数据.js
export const homeObjOne = {
id: 'about',
lightBg: false,
lightText: true,
lightTextDesc: true,
topLine: 'Premium Bank',
headLine: 'Unlimited Transactions with zero fees',
description: 'Get access to our exclusive app that allows you to send unlmited transactions without getting charged any fees.',
buttonLabel: 'Get started',
imgStart: false,
img: require('../../images/svg-1.svg'),
alt: 'Car',
dark: true,
primary: true,
darkText: false
}
InfoSection.js
import React from 'react';
import { Button } from '../ButtonCSS';
import {
InfoContainer,
InfoWrapper,
InfoRow,
Column1,
TextWrapper,
TopLine,
Heading,
Subtitle,
BtnWrap,
ImgWrap,
Column2,
Img,
} from './InfoSectionCSS';
const InfoSection = ({
lightBg,
id,
imgStart,
topLine,
lightText,
headLine,
darkText,
description,
buttonLabel,
img,
alt,
primary,
dark,
}) => {
return (
<>
<InfoContainer lightBg={lightBg} id={id}>
<InfoWrapper>
<InfoRow imgStart={imgStart}>
<Column1>
<TextWrapper>
<TopLine>{topLine}</TopLine>
<Heading lightText={lightText}>{headLine}</Heading>
<Subtitle darkText={darkText}>{description}</Subtitle>
<BtnWrap>
<Button
to='home'
smooth={true}
duration={500}
spy={true}
exact='true'
offset={-80}
dark={dark}
primary={primary}
>
{buttonLabel}
</Button>
</BtnWrap>
</TextWrapper>
</Column1>
<Column2>
<ImgWrap>
<Img src={img} alt={alt} />
</ImgWrap>
</Column2>
</InfoRow>
</InfoWrapper>
</InfoContainer>
</>
);
};
export default InfoSection;
Home.js
import React, { useState } from 'react';
import Navbar from '../components/Navbar/Navbar';
import Sidebar from '../components/Sidebar/Sidebar';
import HeroSection from '../components/HeroSection/Hero';
import InfoSection from '../components/InfoSection/InfoSection';
import { homeObjOne, homeObjTwo, homeObjThree } from '../components/InfoSection/Data';
const Home = () => {
const [isOpen, setIsOpen] = useState(false);
const toggle = () => {
setIsOpen(!isOpen);
};
return (
<>
<Sidebar isOpen={isOpen} toggle={toggle} />
<Navbar toggle={toggle} />
<HeroSection />
<InfoSection {...homeObjOne} />
<InfoSection {...homeObjTwo} />
<InfoSection {...homeObjThree} />
</>
);
};
export default Home;
SVG 应该在右侧。
【问题讨论】:
-
你也可以上传Img组件吗?
-
@PramodKumar 它在 Data.js img 中:require('../../images/svg-1.svg'),在 InfoSection.js 中我试图用
-
您可以将 svg 作为 js 对象导入 -
import svg1 from '../../images/svg-1.svg'并将其分配给键 -img: svg1, -
@user2819542 检查anwser,我解决了,但感谢您的回复
标签: javascript reactjs image svg