首页 > 解决方案 > 无法在屏幕 ReactJS 上显示 SVG 图像

问题描述

我正在尝试通过教程学习 React js,并且我创建了一个可重用的组件,可以在其中显示信息,但无法显示我的 svg 图像。看起来像这样-

在此处输入图像描述

查看图像如何不显示和alt显示。

为此,我制作了三个文件 1) index.js- 呈现 reactJS

const InfoSection = ({
    lightBg,
    imgStart,
    topLine,
    lightText,
    headLine,
    description,
    buttonLabel,
    img,
    alt,
    id,
    darkText,
  }) => {
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'>{buttonLabel}</Button>
                        </BtnWrap>
                    </TextWrapper>
                    </Column1>
                    <Column2>
                        <ImgWrap>
                            <Img src={img} alt={alt} />
                        </ImgWrap>
                    </Column2>
                </InfoRow>
            </InfoWrapper>
        </InfoContainer>
    )
}
  1. InfoElements- 由所有样式化的组件和 css 组成,与问题有关,ImgWrapImg这个,
export const ImgWrap = styled.div`
  max-width: 555px;
  height: 100%;
`;

export const Img = styled.img`
  width: 100%;
  margin-top: 0;
  margin-right: 0;
  margin-left: 10px;
  padding-right: 0;
`;
  1. data.js文件-我在哪里传递我的数据
export const homeObjOne = {
    id: 'about',
    lightBg: false,
    lightText: true,
    lightTextDesc: true,
    topLine: 'About',
    headLine: 'headline',
    description:
      'description',
    buttonLabel: 'Get Started',
    imgStart: false,
    img: require('../../images/about.svg'),
    alt: 'alt line, if image does not show up',
    dark: false,
    primary: true,
    darkText: false
  };

我尝试了不同的方式在data文件中写入这一行,

img: require('../../images/about.svg')

这里的路径是正确的,否则 react 会出错。我require在这里使用,因为这就是我正在关注的教程中的完成方式。

我究竟做错了什么?如何让图像显示?

标签: javascripthtmlcssreactjssvg

解决方案


我正在做同样的练习,我得到了完全相同的错误。

我以不同的方式做到了,使用导入 import homeObjOneImg from "../../images/svg-3.svg";然后设置img: homeObjOneImg

import homeObjOneImg from "../../images/svg-3.svg";

export const homeObjOne = {
    id: 'about',
    lightBg: true,
    lightText: false,
    lightTextDesc: false,
    topLine: 'topLine',
    headLine: 'headLine',
    description: 'description',
    buttonLabel: 'buttonLabel',
    imgStart: false,
    img: homeObjOneImg,
    alt: 'alt',
    dark: false,
    primary: false,
    darkText: true
}

推荐阅读