如何在GatsbyJS项目中显示图像? [英] How to show images in a GatsbyJS project?

查看:157
本文介绍了如何在GatsbyJS项目中显示图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何显示图像?在下面无法正确显示.

How to show images? It can not be shown correctly below.

src/components/Header.js文件中:

<img src="../images/logo.png" style={{width:"112",height:"28"}} />

推荐答案

将资产直接导入文件中

import React from "react"
import logo from "./logo.png" // Tell Webpack this JS file uses this image

console.log(logo) // /logo.84287d09.png

function Header() {
  // Import result is the URL of your image
  return <img src={logo} alt="Logo" />
}

export default Header

之所以如此,是因为它可以通过Webpack捆绑管道(例如,压缩,数据URL,缓存清除文件名哈希等.

The reason this is best is that it enables optimizations through the Webpack bundling pipeline, e.g. compression, data URLs, cache busting filename hashes, etc.

这对于图像以外的文件最有用.

This is mostly useful for files other than images.

您可以在项目的根目录下创建一个名为static的文件夹. 您放入该文件夹的每个文件都将被复制到public 文件夹.例如.如果将名为sun.jpg的文件添加到static文件夹, 它将被复制到public/sun.jpg

You can create a folder named static at the root of your project. Every file you put into that folder will be copied into the public folder. E.g. if you add a file named sun.jpg to the static folder, it’ll be copied to public/sun.jpg

您可以在代码中引用静态文件夹中的资产,而无需 特殊要求:

You can reference assets from the static folder in your code without anything special required:

render() {
  // Note: this is an escape hatch and should be used sparingly!
  // Normally we recommend using `import` for getting asset URLs
  // as described in the "Importing Assets Directly Into Files" page.
  return <img src={'logo.png'} alt="Logo" />;
}


Corey的答案引用了 部分,该部分很有用,但不需要加载图像.


Corey's answer quotes the "Add custom webpack config" section of the Gatsby documentation, which is useful but unnecessary to load images.

这篇关于如何在GatsbyJS项目中显示图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆