构建自定义图片组件
Astro 提供了两个内置组件,可用于显示和优化图片。<Picture>
组件允许你显示响应式图片并使用不同的格式和尺寸。<Image>
组件将优化你的图片并允许你传递不同的格式和质量属性。
¥Astro provides two built-in components that you can use to display and optimize your images. The <Picture>
component allows you to display responsive images and work with different formats and sizes. The <Image>
component will optimize your images and allow you to pass in different formats and quality properties.
当你需要 <Picture>
和 <Image>
组件当前不支持的选项时,你可以使用 getImage()
功能创建自定义组件。
¥When you need options that the <Picture>
and <Image>
components do not currently support, you can use the getImage()
function to create a custom component.
在本节中,你将使用 getImage()
功能 创建你自己的自定义图片组件,该组件根据媒体查询显示不同的源图片。
¥In this recipe, you will use the getImage()
function to create your own custom image component that displays different source images based on media queries.
¥Recipe
-
Create a new Astro component and import the
getImage()
function -
Create a new component for your custom image.
MyCustomComponent.astro
will receive threeprops
fromAstro.props
. ThemobileImgUrl
anddesktopImgUrl
props are used for creating your image at different viewport sizes. Thealt
prop is used for the image’s alt text. These props will be passed wherever you render your custom image components. Add the following imports and define the props that you will use in your component. You can also use TypeScript to type the props. -
Define each of your responsive images by calling the
getImage()
function with your desired properties. -
Create a
<picture>
element that generates asrcset
with your different images based on your desired media queries. -
Import and use
<MyCustomImageComponent />
in any.astro
file. Be sure to pass the necessary props for generating two different images at the different viewport sizes: