【问题标题】:Cannot understand how background-image url works in Gatsby.js无法理解背景图像 url 在 Gatsby.js 中的工作方式
【发布时间】:2020-05-30 02:19:49
【问题描述】:

我正在学习盖茨比。我有一个名为 Hero 的组件,用于显示我正在构建的博客的横幅。

import React from 'react';
import styled from '@emotion/styled';
import { Link, graphql, useStaticQuery } from 'gatsby';

const ImageBackground = styled('div')`
  background-image: url('images/plans-background.jpg'); <--- this url doesn't make sense to me
  background-position: top 20% center;
  background-size: cover;
  /* background-color: red; */
`;

const Hero = () => {
  return (
    <ImageBackground>
      <h1>Frontend Masster dsfsdfsd</h1>
      <p>
        hello
        <Link to="/about">learn about me</Link>
      </p>
    </ImageBackground>
  );
};

export default Hero;

我正在使用屏幕截图来显示文件夹结构

根据结构,为了到达背景图片我需要一个这样的url

`../../../static/images/plans-background.jpg`

这就是 IDE 在尝试访问图像文件时提示我输入的内容。但是,此网址无法按预期工作。没有显示背景图像。我把它改成了

`images/plans-background.jpg`

背景图片神奇地出现了。

所以我不明白为什么这个网址有效。是文件夹static 有什么特别之处,还是盖茨比在幕后做了什么?

另外,当我打开 devtool 检查加载的资源时,我没有找到这个 static 文件,也没有找到背景图像文件。

我真的很想了解这些部分是如何协同工作的

【问题讨论】:

  • 您的gatsby-config 上是否正确配置了gatsby-source-filesystem
  • @wentjun 嗨,我正在学习教程,在教程中,gatsby-source-filesystem 的配置只是非常简单。它看起来像这样 ` { resolve: 'gatsby-source-filesystem', options: { name: 'posts', path: 'posts', }, },`
  • 这能回答你的问题吗? Gatsby: Set background image with CSS

标签: javascript html css reactjs gatsby


【解决方案1】:

是的,这是 /static 中您的资产的预期行为,请在文档中了解更多信息:Using the Static Folder

但是,添加图像并不是最佳做法,因为它们不会使用 Gatsby 的构建时图像处理和 gatsby-image 进行优化。

文档也有很好的资源:@​​987654322@ 或 Working with images in Gatsby

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 2015-07-30
    • 2021-04-09
    相关资源
    最近更新 更多