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

如何在React中给背景图片叠加线性渐变?CRA新手项目实现问题

修复方案

你代码的核心问题是JSX中style属性的绑定逻辑错误,你已经提前定义好了style样式对象,不需要再额外嵌套一层对象,直接绑定即可。

修正后的完整代码如下:

MainView 组件代码

import NavBar from "./NavBar";
// import SocialMedia from "../socialmedia/SocialMedia";
import classes from './MainView.module.css';
import background from '../../img/pic2.jpg';

function MainView() {
    const style = {
        backgroundImage: `linear-gradient( rgba(8, 8, 37, 0.85), rgba(0, 15, 80, 0.675)), url("${background}")`
    };

    return (
        <>
            <NavBar />
            <section 
                style={style}
                className={classes.top}
            >
                <div>
                    <p>My Name</p>
                    <p>Full Stack Web Developer</p>
                </div>
            </section>
            {/* <SocialMedia /> */}
        </>
    )
}

export default MainView;

CSS 代码(无需修改,保持原有内容即可)

@import url('https://fonts.googleapis.com/css2?family=Montserrat&family=Trispace&display=swap');

.top {
    background-repeat: no-repeat;
    background-position: center bottom;
    background-size: cover;
    width: 100%;
    height: 100vh;
    font-family: 'Montserrat', sans-serif;
}

如果修改后背景仍不显示,确认../../img/pic2.jpg相对于当前MainView组件文件的路径是正确的即可,CRA会自动处理import引入的静态资源路径,图片放在src目录下的img文件夹符合要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 09:57:02