【问题标题】:React JS styled-components importing images from public folderReact JS styled-components 从公共文件夹导入图像
【发布时间】:2021-11-30 19:40:11
【问题描述】:

我一直在尝试将图像设置为样式组件中公共文件夹中的背景图像。 我试过了

import styled from "styled-components";
import Background from 'process.env.PUBLIC_URL + /images/background.svg'

export const HomeContainer = styled.section`
  height: 100vh;
  max-width: 100vw;
  background-image: url(${Background});
  background-repeat: no-repeat;
  background-size: cover;
`;

等等

import styled from "styled-components";

export const HomeContainer = styled.section`
  height: 100vh;
  max-width: 100vw;
  background-image: url('process.env.PUBLIC_URL + /images/background.svg');
  background-repeat: no-repeat;
  background-size: cover;
`;

如何导入? 提前致谢

【问题讨论】:

    标签: javascript css reactjs styled-components styling


    【解决方案1】:

    试试这个,它对我有用。

    import bgImage from "../images/background.png";
    
    const Wrapper = styled.div`
      background-image: url(${bgImage});
    `
    

    【讨论】:

    • 它对我不起作用。
    【解决方案2】:

    我用谷歌搜索过,但仍然没有像你一样的东西。

    所以我决定使用道具:

    import styled from "styled-components";
    
    const HomeContainer = styled.section`
      height: 100vh;
      max-width: 100vw;
      background-image: url(${ ({Background}) => Background });
      background-repeat: no-repeat;
      background-size: cover;
    `;
    
    const App = () => {
      return (
        <HomeContainer Background={ process.env.PUBLIC_URL + 'where your image at' } />
      )
    }
    

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案3】:

    我强烈建议您使用基本路径配置 jsconfig 文件

    {
      "compilerOptions": {
          "jsx": "react",
          "baseUrl": "./",
      }
    }
    

    然后只需通过 import img from "public/images/whatever.png 访问您的图片

    【讨论】:

      猜你喜欢
      • 2020-02-06
      • 2021-08-26
      • 2018-06-23
      • 1970-01-01
      • 2020-04-20
      • 2017-06-17
      • 1970-01-01
      • 2022-07-28
      • 2021-06-18
      相关资源
      最近更新 更多