You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Next.js中如何将图片作为props传递给styled-components设置背景?

问题原因
  • Next.js 本地图片导入特性:从public目录引入的本地图片资源,导入后得到的是包含src、width、height属性的资源对象,不是直接的路径字符串,直接把整个对象传入background-image的url()中会导致路径解析失败。
  • CSS语法错误:样式定义中的width: 100缺少单位(如%、px等),会导致容器宽度规则不生效。
修复方案

只需要做两处调整即可:

  1. 传递图片对象的src属性给样式组件,而非整个图片对象
  2. 补全width属性的单位,可额外添加背景适配属性优化显示效果

修改后的ShowCase组件代码

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

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

export default ShowCase

修改后的样式组件代码

import styled from 'styled-components'

export const Hero = styled.div`
  background-image: url(${(props) => props.image});
  width: 100%;
  height: 300px;
  /* 以下为可选优化属性,让背景图适配容器 */
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
`

内容的提问来源于stack exchange,提问作者Ricardo de Paula

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 11:48:04