块编辑器开发文档

ResponsiveWrapper

💡 云策文档标注

概述

ResponsiveWrapper 是一个 WordPress 组件,用于包装子元素并保持其宽高比在调整大小时不变。它支持图片和 SVG 元素,并提供属性如 naturalWidth 和 naturalHeight 来控制固有尺寸。

关键要点

  • ResponsiveWrapper 组件用于保持子元素的宽高比,适用于响应式设计。
  • 支持包装图片元素,需提供 naturalWidth 和 naturalHeight 属性以计算宽高比。
  • 包装 SVG 元素时,需确保 SVG 具有 viewbox 和 preserveAspectRatio 属性,否则可能无法正确缩放。
  • 提供 isInline 属性,可设置为 true 以使用 span 标签代替 div 标签。
  • children 属性是必需的,指定要包装的 React 元素。

代码示例

import { ResponsiveWrapper } from '@wordpress/components';

const MyResponsiveWrapper = () => (
    <ResponsiveWrapper naturalWidth={ 2000 } naturalHeight={ 680 }>
        <img
            src="https://s.w.org/style/images/about/WordPress-logotype-standard.png"
            alt="WordPress"
        />
    </ResponsiveWrapper>
);

注意事项

当包装 SVG 元素时,如果无法获取 naturalWidth 和 naturalHeight,SVG 可能会无限缩放,除非指定了 height 和 width 属性。


📄 原文内容

A wrapper component that maintains its aspect ratio when resized.

Usage

import { ResponsiveWrapper } from '@wordpress/components';

const MyResponsiveWrapper = () => (
    <ResponsiveWrapper naturalWidth={ 2000 } naturalHeight={ 680 }>
        <img
            src="https://s.w.org/style/images/about/WordPress-logotype-standard.png"
            alt="WordPress"
        />
    </ResponsiveWrapper>
);

Usage with SVG elements

When passing an SVG element as the <ResponsiveWrapper />‘s child, make sure that it has the viewbox and the preserveAspectRatio set.

When dealing with SVGs, it may not be possible to derive its naturalWidth and naturalHeight and therefore passing them as propertied to <ResponsiveWrapper />. In this case, the SVG simply keeps scaling up to fill its container, unless the height and width attributes are specified.

Props

children: React.ReactElement

The element to wrap.

  • Required: Yes

isInline: boolean

If true, the wrapper will be span instead of div.

  • Required: No
  • Default: false

naturalHeight: number

The intrinsic height of the element to wrap. Will be used to determine the aspect ratio.

  • Required: No

naturalWidth: number

The intrinsic width of the element to wrap. Will be used to determine the aspect ratio.

  • Required: No