reactjs 将正文背景图像连接到next.js中的状态

8ehkhllq  于 2023-01-30  发布在  React
关注(0)|答案(2)|浏览(75)

我正在尝试使用Next.js制作一个番茄定时器,我需要将body的背景图像连接到一个状态。但是我的代码不起作用。
我用这个代码来更新身体样式:

import { VscDebugRestart } from "react-icons/vsc";
import { IoMdSettings } from "react-icons/io";
import { AiFillPlayCircle, AiFillPauseCircle } from "react-icons/ai";
import { FaTasks } from "react-icons/fa";
import { Modal } from "@/components";
import { useModal } from "@/components/modal";
import { useEffect } from "react";

const Timer = () => {
    const settingsModal = useModal();
    const tasksModal = useModal();

    // Update
    useEffect(() => {
        document.body.style.background =
            "url('/images/city-3.jpg') no-repeat center center fixed;";
    }, []);

    return (
        <div className="timer">
            <div className="session-options">
                <button className="btn">studying</button>
                <button className="btn">short break</button>
                <button className="btn">long break</button>
            </div>
            <h1 className="time-info">1:30:00</h1>
            <div className="options">
                <AiFillPlayCircle className="btn-icon" />
                {/* <AiFillPauseCircle className="btn-icon" /> */}
                <VscDebugRestart className="btn-icon" />
                <IoMdSettings
                    className="btn-icon"
                    onClick={settingsModal.open}
                />
                <FaTasks className="btn-icon" />
            </div>
            <Modal modal={settingsModal}>settings</Modal>
        </div>
    );
};

export default Timer;

但样式不适用,我看不到任何失败的图像请求。(我肯定该图像存在)我可以做些什么来修复它?或者有任何其他的解决方案,使图像适合在背景中,即使大小改变?

xam8gpfp

xam8gpfp1#

删除背景字符串中的分号,它不是CSS

document.body.style.background = "url('/images/city-3.jpg') no-repeat center center fixed"
b5lpy0ml

b5lpy0ml2#

真是个错误!不管怎么说,谢谢你的帮助。我修复了它,并添加了功能:

const [bgImageName, setBgImageName] = useState<string | undefined>(
        undefined
    );

    useEffect(() => {
        setBgImageName("city-1.jpg");
    }, []);

    useEffect(() => {
        document.body.style.background = ` rgba(0, 0, 0, .3) url("/images/${bgImageName}") no-repeat center center fixed`;
        document.body.style.backgroundSize = "cover";
        document.body.style.backgroundBlendMode = "darken";
    }, [bgImageName]);

相关问题