【问题标题】:Backgroung-image as a prop in a styled component - Typescript and Next.js背景图像作为样式组件中的道具 - Typescript 和 Next.js
【发布时间】:2022-03-14 20:26:13
【问题描述】:

如何在 Typescript/Next.js 项目的样式组件中使用 backgroung-image,作为 prop 传递?

我试过 styled.ts

type Props = {
  img?: string
}

export const Wrapper = styled.div<Props>`
  width: 300px;
  height: 300px;
  align-items: center;
  background-image: url(${ props => props.img });
  background-size: cover;
`

我的组件是 HomeCard.tsx:

// ...
type Props = {
  children?: ReactNode
  title: string
  img: string
}

const HomeCard = ({children, title, img}: Props) => {
  return(
    <Wrapper img={img}>         
        {children}
    </Wrapper>
  )
}

图片源在index.js上调用:

import img1 from '../../public/test.jpg'
// ...
<HomeCard img={img1}>


但是浏览器上的输出是:

background-image: url(src:/_next/static/media/test.5f344d84.jpg;height:2667px;width:4000px;blur-data-u-r-l:/_next/image? url=%2F_next%2Fstatic%2Fmedia%2Ftest.5f344d84.jpg&w=8&q=70;);

我尝试使用props.img.replace('src:','') 删除它,但不起作用。

我猜我的错误在于输入内容。

Output

【问题讨论】:

  • 尝试在图像源中传递图像路径,即&lt;HomeCard img="/test.jpg"&gt;

标签: javascript reactjs typescript next.js


【解决方案1】:

试试这个

export const Wrapper = styled.div<Props>`
  width: 300px;
  height: 300px;
  align-items: center;
  background-image: url("/test.jpg");
  background-size: cover;
`

图像文件需要在公共文件夹中??

【讨论】:

    猜你喜欢
    • 2021-11-02
    • 2021-12-04
    • 2018-02-03
    • 2020-03-28
    • 2021-09-13
    • 1970-01-01
    • 2022-10-13
    • 2019-04-13
    • 2019-05-24
    相关资源
    最近更新 更多