【问题标题】:React, Show images using style-component反应,使用样式组件显示图像
【发布时间】:2021-01-11 10:44:41
【问题描述】:

我有一个关于动态分配图像的问题。

我尝试按每个案例显示每个图像(取决于每个数据的类型和总数)。

但是这段代码不起作用。

export default function Title() {
    let image =
  "../../../assets/images/situations/situation_" + totalCount + ".png";
    return (
        <>
        {types[totalCount - 1] === "situation" ? 
        <SituationTitleStyled img={image}>
        ...
        </SituationTitleStyled>
       }
       </>
    )
}

const SituationTitleStyled = styled.div`
    ...
    background: url(${(props) => props.image});
`;

否则,如果变量“image”是像“https://mdn.mozillademos.org/files/7693/catfront.png”这样的绝对路径,那么它可以工作。

我不知道我该如何工作以及使用绝对路径和相对路径之间的区别是什么。 :0

【问题讨论】:

    标签: reactjs image


    【解决方案1】:

    路径应该由webpack生成:

    您可以直接在 JavaScript 模块中导入文件。这告诉 webpack 将该文件包含在包中。与 CSS 导入不同,导入文件会为您提供一个字符串值。该值是您可以在代码中引用的最终路径,例如作为图像的 src 属性或 PDF 链接的 href。

    所以在你的代码中你可以直接调用require:

    let image = require("../../../assets/images/..." + totalCount + ".png");
    

    几乎见duplicated question

    【讨论】:

      猜你喜欢
      • 2021-07-01
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      • 2021-09-18
      • 2022-10-03
      • 2020-03-01
      • 1970-01-01
      • 2015-04-30
      相关资源
      最近更新 更多