块编辑器开发文档

💡 云策文档标注

概述

本文档介绍了 WordPress 核心视口数据包(core/viewport)中的选择器 isViewportMatch,用于根据视口查询判断当前设备类型,例如移动端或非移动端。

关键要点

  • isViewportMatch 选择器返回布尔值,表示视口是否匹配给定的查询字符串。
  • 查询字符串包含操作符和断点名称,默认操作符为 >=,用于定义视口条件。
  • 此包中的操作不应直接使用,主要关注选择器功能。

代码示例

import { store as viewportStore } from '@wordpress/viewport';
import { useSelect } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
const ExampleComponent = () => {
    const isMobile = useSelect(
        ( select ) => select( viewportStore ).isViewportMatch( '< small' ),
        []
    );

    return isMobile ? (
        <div>{ __( 'Mobile' ) }</div>
    ) : (
        <div>{ __( 'Not Mobile' ) }</div>
    );
};

注意事项

参数 state 为 ViewportState 对象,query 为 ViewportQuery 字符串,返回值为布尔类型。


📄 原文内容

Namespace: core/viewport.

Selectors

isViewportMatch

Returns true if the viewport matches the given query, or false otherwise.

Usage

import { store as viewportStore } from '@wordpress/viewport';
import { useSelect } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
const ExampleComponent = () => {
    const isMobile = useSelect(
        ( select ) => select( viewportStore ).isViewportMatch( '< small' ),
        []
    );

    return isMobile ? (
        <div>{ __( 'Mobile' ) }</div>
    ) : (
        <div>{ __( 'Not Mobile' ) }</div>
    );
};

Parameters

  • state ViewportState: Viewport state object.
  • query ViewportQuery: Query string. Includes operator and breakpoint name, space separated. Operator defaults to >=.

Returns

  • boolean: Whether viewport matches query.

Actions

The actions in this package shouldn’t be used directly.

Nothing to document.