Viewport 是一个用于响应浏览器视口尺寸变化的模块。它会注册自己的 data 模块,并根据一组标准支持的断点上的浏览器媒体查询进行更新。你可以在自己的模块和组件中使用这些数据以及其中包含的高阶组件,来实现依赖视口的行为。
安装
安装该模块
npm install @wordpress/viewport --save
此包假定你的代码将运行在 ES2015+ 环境中。如果你使用的环境对此类语言特性和 API 的支持有限或完全不支持,则应在你的代码中包含 @wordpress/babel-preset-default 附带的 polyfill。
用法
标准断点阈值集合如下:
| 名称 | 像素宽度 |
|---|---|
huge | 1440 |
wide | 1280 |
large | 960 |
medium | 782 |
small | 600 |
mobile | 480 |
Data 模块
Viewport 模块在 core/viewport data 命名空间下注册自身,并从该包中以 store 的形式暴露。
import { select } from '@wordpress/data';
import { store } from '@wordpress/viewport';
const isSmall = select( store ).isViewportMatch( '< medium' );
isViewportMatch 选择器接受单个字符串参数 query。它由一个可选操作符和一个断点名称组成,两者之间用空格分隔。操作符可以是 < 或 >=,默认为 >=。
import { select } from '@wordpress/data';
import { store } from '@wordpress/viewport';
const { isViewportMatch } = select( store );
const isSmall = isViewportMatch( '< medium' );
const isWideOrHuge = isViewportMatch( '>= wide' );
// 等价写法:
// const isWideOrHuge = isViewportMatch( 'wide' );
高阶组件
此包提供一组 HOC,用于编写行为应随视口变化的组件。
ifViewportMatches
高阶组件创建器,创建一个仅在视口查询满足时渲染的新组件。
相关
- withViewportMatches
用法
function MyMobileComponent() {
return <div>I'm only rendered on mobile viewports!</div>;
}
MyMobileComponent = ifViewportMatches( '< small' )( MyMobileComponent );
参数
- query
ViewportQuery:视口查询。
返回值
- 高阶组件。
store
viewport 命名空间的 store 定义。
相关
withViewportMatch
高阶组件创建器,创建一个使用给定 prop 名称进行渲染的新组件,传递给底层组件的值是作为对象值分配的查询结果。
相关
- isViewportMatch
用法
function MyComponent( { isMobile } ) {
return <div>Currently: { isMobile ? 'Mobile' : 'Not Mobile' }</div>;
}
MyComponent = withViewportMatch( { isMobile: '< small' } )( MyComponent );
参数
- queries
ViewportQueries:prop 名称到视口查询的对象。
返回值
- 高阶组件。
为这个包做贡献
这是 Gutenberg 项目中的一个独立包。该项目以 monorepo 形式组织。它由多个自包含的软件包组成,每个包都有特定用途。此 monorepo 中的包会发布到 npm,并被 WordPress 以及其他软件项目使用。
要了解有关为这个包或整个 Gutenberg 项目做贡献的更多信息,请阅读项目的主要 贡献者指南。