Next.js 设置背景图片

Soh*_*aar 8 background-image reactjs next.js

我正在尝试向 next.js 添加背景图像,但无法这样做。我尝试过很多解决方案,内联 scc、style jsx 和其他技术。无法直接写入样式,因为它会出错

\n

错误:

\n
Expected a template literal or String literal as the child of the JSX Style tag (eg: <style jsx>{`some css`}</style>), but got BinaryExpression\n
Run Code Online (Sandbox Code Playgroud)\n

也尝试了这个解决方案,但出现错误:

\n

代码

\n
const img = require("../../assets/images/security-team.jpg");\n\n<div\n  style={{\n    backgroundImage: "url(" + `${require("./path-to-the-image")}` + ")",\n    width: "100%",\n    height:[HEIGHT OF THE IMAGE],\n    backgroundRepeat: "no-repeat",\n    backgroundSize: "cover"\n  }}\n>XXX</div>\n
Run Code Online (Sandbox Code Playgroud)\n

错误

\n
Failed to compile\n./public/121.png 1:0\nModule parse failed: Unexpected character '\xef\xbf\xbd' (1:0)\nYou may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders\n(Source code omitted for this binary file)\n
Run Code Online (Sandbox Code Playgroud)\n

但是,当尝试此代码时,它不会给出错误,并且背景图像也不会显示在网页上。

\n

代码

\n
export default function Home() {\n  \n  let styleConfig = { backgroundimage : '/abc.jpeg' }\n\n  \n  return (\n\n      \n    <div className="container"  style={styleConfig} ></div>\n      \n     \n\n\n      <style jsx>{`\n       \n       \n        .container {\n          min-height: 100vh;\n          padding: 0 0.5rem;\n          display: flex;\n          flex-direction: column;\n          justify-content: center;\n          align-items: center;\n          background-image : "/public/121.png"\n        }\n        \n\n        \n      `}</style>\n\n\n\n      <style jsx global>{`\n        html,\n        body {\n          padding: 0;\n          margin: 0;\n          font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto,\n            Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue,\n            sans-serif;\n        }\n\n        * {\n          box-sizing: border-box;\n        }\n      `}</style>\n    </div>\n  )\n}\n
Run Code Online (Sandbox Code Playgroud)\n

小智 11

NEXT.JS 已提供官方支持,需要两个步骤。

  1. 用具有样式的 div 包裹 Image 组件(将提供示例)。
  2. 为图像组件提供示例中提到的属性。

演示: https: //image-component.nextjs.gallery/background

文档: https: //nextjs.org/docs/api-reference/next/image

代码:https://github.dev/vercel/next.js/blob/canary/examples/image-component/pages/background.js


Ays*_*yse -1

将您的图像保存在公共文件夹中

const img = "/thisImage.png";

    return (
        <div className="image">

            <div>XXX</div>
            <style jsx>
                {`
          .image {
            position: absolute;
            top: 0;
            right: 0;
            left: 0;
            height: 100%;
            background-size: cover;
            background-position: center;
            background-image: url(${img});
          }
        `}
            </style>
        </div>
    )
Run Code Online (Sandbox Code Playgroud)