在Next.js中将图像作为 prop 传递给样式化组件

ca1c2owp  于 2023-05-22  发布在  其他
关注(0)|答案(2)|浏览(129)

我试图通过一个图像设置为我的背景下白色样式组件,但导致一个意外的行为。
英雄组件:

import djEventImg from '@/public/images/dj-event.jpg'
import { Hero } from './ShowCase.styles'

const ShowCase = () => {
  return <Hero image={djEventImg}></Hero>
}

export default ShowCase

样式组件:

import styled from 'styled-components'

export const Hero = styled.div`
  // background image props
  background-image: url(${(props) => props.image});
  width: 100;
  height: 300px;
`
bjp0bcyl

bjp0bcyl1#

我复制你的代码在我的本地mashine和得到一个图像与此代码

  • 英雄组件:*
import djEventImg from '/public/images/dj-event.jpg'
import { Hero } from './ShowCase.styles'

const ShowCase = () => {
  return <Hero image={djEventImg}></Hero>
}

export default ShowCase
  • 样式化组件:*
import styled from 'styled-components'

export const Hero = styled.div`
  background-image: url(${props => props.image.src});
  width: 100%;
  height: 300px;
  background-repeat: no-repeat;
`;
m4pnthwp

m4pnthwp2#

您可以直接将Icon导入到样式化组件中。见以下答案:

import styled from 'styled-components';
import Image from "./yourImage.png";

export const Hero = styled.div`
  // background image props
  background-image: url(${Image.src});
  width: 100;
  height: 300px;
`

相关问题