javascript React JS样式组件从公共文件夹导入图像

z9zf31ra  于 2023-03-16  发布在  Java
关注(0)|答案(4)|浏览(136)

我一直在尝试将styled-components中公共文件夹中的图像设置为background-image。

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;
`;

我怎么导入呢?先谢谢了

gg58donl

gg58donl1#

试试这个,对我很有效。

import bgImage from "../images/background.png";

const Wrapper = styled.div`
  background-image: url(${bgImage});
`
de90aj5v

de90aj5v2#

我在谷歌上搜索过了,但还是没有像你一样的。
所以我决定用 prop :

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' } />
  )
}
kuhbmx9i

kuhbmx9i3#

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

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

然后只需import img from "public/images/whatever.png即可访问您的映像

fhg3lkii

fhg3lkii4#

background-image: url(${process.env.PUBLIC_URL}/images/background.svg);

用这个

相关问题