WP DEVELOP

EP153. “BlockControls 文字对齐与 Block 预览/Description”

首页 WordPress 开发课程 GUTENBERG BLOCK 入门(block.json) · EP153
约 15 分钟· #EP153#GUTENBERG BLOCK 入门(block.json)
🔒 登录后可标记已读

Quiz Block 类型的收尾一讲:加上文字对齐(左/中/右)的工具栏选项——跟 EP152 的背景色选择器同一个套路,只是这次用 BlockControls + AlignmentToolbar(出现在点击 Block 后浮在内容正上方的那条内联工具栏,而不是右侧检查器面板)。再补两个不影响功能、但能让 Block 在「新增区块」面板里看起来更完整的小细节:example 属性让鼠标悬停在 Block 缩略图上时能实时预览一份带示例数据的渲染效果,description 属性给右侧面板加一行说明文字。这是这门课 Quiz Block 章节的最后一讲,下一讲开始做 Featured Professor 这个新 Block 类型。


涉及文件

  • wp-content/plugins/are-you-paying-attention/src/index.js (修改)
  • wp-content/plugins/are-you-paying-attention/src/frontend.js (修改)

代码实现

src/index.js:新增 theAlignment 属性 + BlockControls/AlignmentToolbar + example/description

import { TextControl, Flex, FlexBlock, FlexItem, Button, Icon, PanelBody, PanelRow, ColorPicker } from "@wordpress/components"
import { InspectorControls, BlockControls, AlignmentToolbar } from "@wordpress/block-editor"
import { ChromePicker } from "react-color"

// ...(function() {...})() 全局锁定逻辑不变,见 EP145...

wp.blocks.registerBlockType("ourplugin/are-you-paying-attention", {
  title: "Are You Paying Attention?",
  icon: "smiley",
  category: "common",
  attributes: {
    question: { type: "string" },
    answers: { type: "array", default: [""] },
    correctAnswer: { type: "number", default: undefined },
    bgColor: { type: "string", default: "#EBEBEB" },
    theAlignment: { type: "string", default: "left" }
  },
  description: "Give your audience a chance to prove their comprehension.",
  example: {
    attributes: {
      question: "What is my name?",
      correctAnswer: 3,
      answers: ["Meowsalot", "Barksalot", "Purrsloud", "Brad"],
      theAlignment: "center",
      bgColor: "#CFE8F1"
    }
  },
  edit: EditComponent,
  save: function (props) {
    return null
  }
})

function EditComponent(props) {
  // ...updateQuestion / deleteAnswer / markAsCorrect 不变...

  return (
    <div className="paying-attention-edit-block" style={{ backgroundColor: props.attributes.bgColor }}>
      <BlockControls>
        <AlignmentToolbar value={props.attributes.theAlignment} onChange={x => props.setAttributes({ theAlignment: x })} />
      </BlockControls>
      <InspectorControls>
        <PanelBody title="Background Color" initialOpen={true}>
          <PanelRow>
            <ChromePicker color={props.attributes.bgColor} onChangeComplete={x => props.setAttributes({ bgColor: x.hex })} disableAlpha={true} />
          </PanelRow>
        </PanelBody>
      </InspectorControls>
      {/* ...TextControl / 答案列表 / Add another answer 按钮不变... */}
    </div>
  )
}

src/frontend.js:把 theAlignment 接到前台最外层 <div> 的行内样式

<div className="paying-attention-frontend" style={{backgroundColor: props.bgColor, textAlign: props.theAlignment}}>

关键改动点:

  • 新增 theAlignment: {type: "string", default: "left"} 属性——取名 theAlignment 而不是直接叫 alignment,是为了避开 WordPress/Gutenberg 里 align/alignment 这类名字可能跟内建机制冲突的顾虑(沿用作者的命名习惯)
  • import {InspectorControls, BlockControls, AlignmentToolbar} from "@wordpress/block-editor"BlockControlsAlignmentToolbar 都来自跟 InspectorControls 同一个包
  • BlockControls vs InspectorControls 的区别InspectorControls(EP152)渲染在编辑器右侧的检查器面板;BlockControls 渲染在点击 Block 后浮在内容正上方的那条内联工具栏(跟加粗/斜体这些默认工具栏是同一个位置)——用哪个纯粹看这个设置更适合哪种交互习惯,写法上都是「把组件塞进 JSX 某处,WordPress 自动搬到正确位置」,不需要手写定位逻辑
  • <AlignmentToolbar value={...} onChange={x => props.setAttributes({theAlignment: x})} />AlignmentToolbar 是 WordPress 内建的现成组件,专门提供左/中/右对齐图标,value 传当前值、onChange 拿到新值后写回 attribute——这里的事件名是常规的 onChange(不是 EP152 颜色选择器那个特殊的 onChangeComplete
  • 编辑器预览区没有theAlignment 应用到那些 TextControl 输入框上——作者认为编辑输入框跟着一起变对齐看起来会很怪,所以只在前台生效
  • 前台 frontend.js 的最外层 <div>style 对象里加一个 textAlign: props.theAlignment——注意 CSS 属性 text-align 在 JS 对象里要写成驼峰式 textAlign
  • example 属性(顶层,跟 title/icon/attributes 同级):给 attributes 提供一套示例值,WordPress 会真的用这套数据完整渲染一次这个 Block(不是静态截图,是实时用真实代码 + 这份示例数据跑出来的渲染结果),显示在「新增区块」面板里鼠标悬停在这个 Block 上出现的预览缩略图里——纯粹是可选的锦上添花功能,不写也完全不影响功能
  • description 属性(顶层,跟 example 同级):一段字符串,点击 Block 后会显示在右侧检查器面板的说明区域,帮助后续使用这个 Block 的人(也可能是未来的自己)快速理解这个 Block 是干什么用的

[截图:点击 Quiz Block 后浮在内容正上方的对齐工具栏(BlockControls + AlignmentToolbar,左/中/右三个图标)]

[截图:在"新增区块"插入面板里鼠标悬停在 Are You Paying Attention 缩略图上,弹出的 example 实时预览效果]


Hook / Function 速查

名称类型用途
BlockControls@wordpress/block-editor 组件把内部内容渲染到点击 Block 后浮现的内联工具栏(Block 内容正上方)
AlignmentToolbar@wordpress/block-editor 组件WordPress 内建的左/中/右对齐图标工具组
exampleregisterBlockType 顶层属性)配置项提供示例 attributes 数据,驱动「新增区块」面板悬停预览的实时渲染
descriptionregisterBlockType 顶层属性)配置项在右侧检查器面板显示这个 Block 的说明文字

常见坑

  • 属性命名直接叫 alignment——容易跟 WordPress/Gutenberg 里跟对齐相关的内建概念混淆,改用 theAlignment 这类更独特的名字更安全
  • theAlignment 也应用到编辑器里的输入框上,让编辑体验本身也跟着左右居中变化——观感别扭,作者的做法是只让前台展示跟随对齐设置,编辑区保持固定
  • example 里的 attributes 值跟真实数据结构对不上(比如漏了某个字段、类型不对)——预览渲染可能报错或者显示不完整,写 example 时要跟真实 attributes 定义逐一对应

Sources

Udemy:

  • Become a WordPress Developer: Unlocking Power With Code — Section 25, EP153