【问题标题】:Next.js return (failed)net::ERR_UNKNOWN_URL_SCHEME for imported imagesNext.js 为导入的图像返回(失败)net::ERR_UNKNOWN_URL_SCHEME
【发布时间】:2021-11-15 12:28:31
【问题描述】:

我正在使用 Next.js + styled-components + TypeScript。我想使用 background-image: url() 从 src 文件夹中的 assets 文件夹中导入图像。在网络选项卡中,当我查找图像时,它会显示状态:

(failed)net::ERR_UNKNOWN_URL_SCHEME 并且 url 是 src:/_next/static/image/public/right.e158775f9c1cf296e36177bfb86a5ced.svg;height:32px;width:32px;

不显示图像。

资产文件夹存在于/src/assets/left.svg

如果我在index.tsx 文件中导入相同的图像并在Image 组件中渲染它,它工作正常。

// styles.tsx

import styled from 'styled-components';
import Left from '../../assets/left.svg';
import Right from '../../assets/right.svg';

export const SwiperWrapper = styled.div`
  margin-top: 2.5rem;
  position: relative;
  .swiper-position {
    position: static !important;
  }
  .swiper-button-next:after,
  .swiper-button-prev:after {
    content: '';
  }
  .swiper-button-prev {
    background-image: url(${Left});
    background-repeat: no-repeat;
    background-size: 100% auto;
    background-position: center;
    -webkit-tap-highlight-color: transparent;
    top: 100%;
  }
  .swiper-button-next {
    background-image: url(${Right});
    background-repeat: no-repeat;
    background-size: 100% auto;
    background-position: center;
    -webkit-tap-highlight-color: transparent;
  }
`;

【问题讨论】:

    标签: css reactjs next.js styled-components


    【解决方案1】:

    这是因为在 Nextjs 中,静态文件是从根目录中的“公共”文件夹提供的。我建议您将图像存储在此文件夹中并用“/”引用它们

    例如background-image: url('/Right');

    【讨论】:

    • 阅读更多here
    • 非常感谢!它的工作,并感谢分享链接以及
    【解决方案2】:

    您可以直接使用,而不是将我们所有的图像移动到公共文件夹

    background-image: url(${Left.src});
    

    这对我有用:)

    注意: 实际上Left 将是一个对象,如果您尝试console.log 它,它将类似于:

    {
    blurDataURL: "/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fleft.475f00e5.png&w=8&q=70"
    height: 1321
    src: "/_next/static/media/left.475f00e5.png"
    width: 1321
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 2019-11-21
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 2018-12-09
      • 2021-08-08
      相关资源
      最近更新 更多