【问题标题】:Passing image as props to styled components in Next.js将图像作为道具传递给 Next.js 中的样式化组件
【发布时间】:2021-11-02 12:43:30
【问题描述】:

我正在尝试传递一个图像以在 Next whit Styled Components 中设置为我的背景,但会导致意外行为。

英雄组件:

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

【问题讨论】:

  • “但导致意外行为” ...什么意外行为?请在问题中添加与问题相关的文本。 PS:很可能您需要通过 djEventImg.src 代替。此外,可以直接提供存储在public 目录中的图像。 [Ref.]所以你甚至不需要导入图像---&lt;Hero image="/images/dj-event.jpg" /&gt;
  • 就这么简单,我用 HTML url(src:/_next/static/image/src/public/images/dj-event.d431960f340929359ffb5934fc6d628a.jpg;height:851px;width:1280px;blur-data-u-r-l:/_next/image?url=%2F_next%2Fstatic%2Fimage%2Fsrc%2Fpublic%2Fimages%2Fdj-event.d431960f340929359ffb5934fc6d628a.jpg&amp;w=8&amp;q=70;)
  • @RicardodePaula 您是否按照建议尝试过&lt;Hero image="/images/dj-event.jpg" /&gt;?它对你有用吗?
  • 我在 Html 中有这个`background-image: url(/images/dj-event.jpg)`,但它仍然不起作用。
  • 我最初评论的最后一部分可能对您无效。查看您生成的 CSS,我相信您的 src 文件夹 (so static file serving from there won't work) 中有 public。试试这个:&lt;Hero image={djEventImg.src} /&gt;

标签: next.js styled-components


【解决方案1】:

我在我的本地 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;
`;

【讨论】:

  • 非常感谢!这是我的第一个 Next 项目。在 ReactJS 中,我不需要将 .src 放在最后。
猜你喜欢
  • 2017-08-17
  • 2018-02-03
  • 2020-10-28
  • 1970-01-01
  • 2023-01-04
  • 1970-01-01
  • 2019-09-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多