React中Styled Component背景图片无法加载问题求助
解决styled-components传递图片背景不加载的问题
问题根源
- 组件间Props传递名称不匹配,导致图片地址未正确传入子组件
- 背景图容器缺少必要样式,无法正常渲染背景图
修复方案
1. 修正Props传递名称
在App.js中,给DestCard组件传递Props时,需将参数名改为子组件接收的imgurl:
// 原代码 <DestCard details={details.image} /> // 修改后 <DestCard imgurl={details.image} />
2. 完善背景图容器样式
在Card.style.js中,给CardImage添加高度、背景图适配等样式,确保背景图能正常显示:
// 原代码 export const CardImage= styled.div` background-image: url(${({bg}) => bg}); width: 60px; /* background-size: cover; */ ` // 修改后 export const CardImage= styled.div` background-image: url(${({bg}) => bg}); width: 60px; height: 100%; /* 与父容器高度一致 */ background-size: cover; /* 让背景图铺满容器 */ background-position: center; /* 居中显示背景图 */ `
完整修改后代码
App.js
import React from "react"; import DestCard from "./Card"; import { Grid } from "@mui/material"; const cardInfo = [ { image: "https://upload.wikimedia.org/wikipedia/commons/b/bf/LeBron_James_-_51959723161_%28cropped%29.jpg", title: "Lebron James", text: "THE GOAT", }, { image: "https://upload.wikimedia.org/wikipedia/commons/a/aa/TechCrunch_Disrupt_2019_%2848834853256%29_%281%29.jpg", title: "Stephen Curry", text: "3 pointer GOD", }, { image: "https://upload.wikimedia.org/wikipedia/commons/b/bf/LeBron_James_-_51959723161_%28cropped%29.jpg", title: "Lebron James", text: "THE GOAT", }, { image: "https://upload.wikimedia.org/wikipedia/commons/a/aa/TechCrunch_Disrupt_2019_%2848834853256%29_%281%29.jpg", title: "Stephen Curry", text: "3 pointer GOD", } ]; function App() { return ( <div> <Grid container spacing={{ xs: 2, md: 3 }} columns={{ xs: 4, sm: 8, md: 12 }}> {cardInfo.map((details, index) => ( <Grid item xs={2} sm={4} md={4} key={index}> <DestCard imgurl={details.image} /> </Grid> ))} </Grid> </div> ) } export default App;
Card.style.js
import styled from "styled-components"; export const StyledCard= styled.div` display: flex; width: 100px; height: 100px; overflow: hidden; box-shadow: 0px 0px 15px -5px; ` export const CardImage= styled.div` background-image: url(${({bg}) => bg}); width: 60px; height: 100%; background-size: cover; background-position: center; `
内容的提问来源于stack exchange,提问作者Tushar Singh
相关产品推荐
相关产品推荐

