跳转到内容

构建自定义图像组件

Astro 提供了两个内置组件,你可以用它们来显示和优化图片。 <Picture> 组件允许你显示响应式图片,并处理不同的格式和尺寸。 <Image> 组件将优化你的图片,并允许你传入不同的格式和质量属性。

当你需要 <Picture><Image> 组件当前不支持的选项时,你可以使用 getImage() 函数来创建一个自定义组件。

在本指南中,你将使用getImage() 函数创建你自己的自定义图片组件,该组件根据媒体查询显示不同的源图片。

  1. 创建一个新的 Astro 组件并导入 getImage() 函数

    src/components/MyCustomImageComponent.astro
    ---
    import { getImage } from "astro:assets";
    ---
  2. 为你的自定义图片创建一个新组件。 MyCustomComponent.astro 将从 Astro.props 接收三个 propsmobileImgUrldesktopImgUrl props 用于在不同视口尺寸下创建图片。 alt prop 用于图片的 alt 文本。 无论你在哪里渲染你的自定义图片组件,这些 props 都会被传入。 添加以下导入并定义你将在组件中使用的 props。 你也可以使用 TypeScript 为 props 添加类型。

    src/components/MyCustomImageComponent.astro
    ---
    import type { ImageMetadata } from "astro";
    import { getImage } from "astro:assets";
    interface Props {
    mobileImgUrl: string | ImageMetadata;
    desktopImgUrl: string | ImageMetadata;
    alt: string;
    }
    const { mobileImgUrl, desktopImgUrl, alt } = Astro.props;
    ---
  3. 通过调用 getImage() 函数并传入你想要的属性,来定义每个响应式图片。

    src/components/MyCustomImageComponent.astro
    ---
    import type { ImageMetadata } from "astro";
    import { getImage } from "astro:assets";
    interface Props {
    mobileImgUrl: string | ImageMetadata;
    desktopImgUrl: string | ImageMetadata;
    alt: string;
    }
    const { mobileImgUrl, desktopImgUrl, alt } = Astro.props;
    const mobileImg = await getImage({
    src: mobileImgUrl,
    format: "webp",
    width: 200,
    height: 200,
    });
    const desktopImg = await getImage({
    src: desktopImgUrl,
    format: "webp",
    width: 800,
    height: 200,
    });
    ---
  4. 创建一个 <picture> 元素,该元素会根据你所需的媒体查询,用你不同的图片生成一个 srcset

    src/components/MyCustomImageComponent.astro
    ---
    import type { ImageMetadata } from "astro";
    import { getImage } from "astro:assets";
    interface Props {
    mobileImgUrl: string | ImageMetadata;
    desktopImgUrl: string | ImageMetadata;
    alt: string;
    }
    const { mobileImgUrl, desktopImgUrl, alt } = Astro.props;
    const mobileImg = await getImage({
    src: mobileImgUrl,
    format: "webp",
    width: 200,
    height: 200,
    });
    const desktopImg = await getImage({
    src: desktopImgUrl,
    format: "webp",
    width: 800,
    height: 200,
    });
    ---
    <picture>
    <source media="(max-width: 799px)" srcset={mobileImg.src} />
    <source media="(min-width: 800px)" srcset={desktopImg.src} />
    <img src={desktopImg.src} alt={alt} />
    </picture>
  5. 在任何 .astro 文件中导入并使用 <MyCustomImageComponent />。 请确保传入必要的 props,以便在不同的视口尺寸下生成两张不同的图片。

    src/pages/index.astro
    ---
    import MyCustomImageComponent from "../components/MyCustomImageComponent.astro";
    import mobileImage from "../images/mobile-profile-image.jpg";
    import desktopImage from "../images/desktop-profile-image.jpg";
    ---
    <MyCustomImageComponent
    mobileImgUrl={mobileImage}
    desktopImgUrl={desktopImage}
    alt="user profile picture"
    />
贡献 社区 赞助