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

React行内样式中同时添加背景图片与线性渐变的方法

问题解决:React组件背景渐变不显示

你的问题主要出在两个核心点,同时还有两处细节错误需要修正:

1. 背景层顺序错误

CSS中background-image的多个值遵循先声明的在上层的堆叠规则,你把图片放在渐变前面,导致图片完全覆盖了渐变,自然看不到效果。正确顺序应该把渐变写在前面,图片放在后面,让渐变叠加在图片上方。

2. 模板字符串换行导致无效CSS

你在模板字符串里给渐变代码加了换行,会生成多余空格,可能导致CSS解析异常。建议把渐变代码压缩成一行,避免格式干扰。

额外细节修正

  • App.jsx中组件函数缺少return语句,无法正常渲染内容
  • 传入的subTitle属性和组件内使用的props.subtitle大小写不匹配,会导致副标题无法显示
  • 需为容器设置明确宽高,并补充背景相关属性(如background-size),确保背景铺满容器

修改后的PastEventCard.jsx代码

import React from "react";
import "./PastEventCard.css";

function PastEventCard(props) {
  return (
    <div
      className="past-event-card"
      style={{
        backgroundImage: `linear-gradient(0deg, rgba(44, 7, 5, 0.6) 0%, rgba(44, 7, 5, 0) 100%), url(${props.imgURL})`,
        backgroundSize: "cover",
        backgroundRepeat: "no-repeat",
        backgroundPosition: "center"
      }}
    >
      <h3 className="card-title">{props.title}</h3>
      <p className="card-subtitle">{props.subTitle}</p>
      <p className="card-description">{props.description}</p>
    </div>
  );
}
export default PastEventCard;

修改后的App.jsx代码

import React from "react";
import "./PastEventSection.css";
import PastEventCard from "./PastEventCard";
import capacitorCardImg from "../assets/capacitor-card-img.jpg";
import theGoldenRecordCardImg from "../assets/the-golden-record-card-img.jpg";
import assiutCollageFairCardImg from "../assets/assiut-collage-fair-card-img.jpg";

function PastEventSection(props) {
  return (
    <section className="past-event-section">
      <PastEventCard
        title="Assiut Collage Fair"
        subTitle="#know_your_future"
        description="lorem50"
        imgURL={assiutCollageFairCardImg}
      />
      <PastEventCard
        title="TEDxYouth@AssiutSTEM2020"
        subTitle="#the_golden_record"
        description="lorem50"
        imgURL={theGoldenRecordCardImg}
      />
      <PastEventCard
        title="TEDxYouth@AssiutSTEM2019"
        subTitle="#capacitor"
        description="lorem50"
        imgURL={capacitorCardImg}
      />
    </section>
  );
}
export default PastEventSection;

补充CSS建议(PastEventCard.css)

为确保容器和文字显示正常,可添加以下样式:

.past-event-card {
  width: 300px;
  height: 400px;
  padding: 2rem;
  color: #fff;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
}

内容的提问来源于stack exchange,提问作者AbdelrahmanAhmed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 05:01:05