You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress Gutenberg自定义菜单块:RichText独立编辑实现方案

解决Gutenberg自定义侧边栏菜单块菜单项无法独立编辑的问题

问题根源是所有RichText组件都绑定了同一个text属性,修改时会同步更新所有项。要实现独立编辑,需要将属性改为数组存储每个菜单项的独立数据,通过循环渲染每个项并绑定对应的数据字段。

修改步骤:

  1. 调整块属性结构:将单个text属性改为menuItems数组,每个元素包含菜单项的唯一标识、显示文本、图标类名、锚点链接等信息,设置合理的默认值。
  2. 循环渲染菜单项:在编辑组件中遍历menuItems数组,为每个项生成对应的RichText组件,绑定各自的文本值和变更处理函数。
  3. 更新属性处理逻辑:编写针对单个菜单项文本的更新函数,修改数组中对应项的文本内容。
  4. 完善保存组件:根据保存的menuItems数据渲染最终的菜单结构。

修改后的完整代码:

import { RichText } from "@wordpress/block-editor"
import { registerBlockType } from "@wordpress/blocks"

registerBlockType("ourblocktheme/sidebarmenucontent", {
  attributes: {
    menuItems: {
      type: 'array',
      default: [
        { id: 'home', label: '首页', icon: 'bi-house-door', scrollNav: '0', href: '#home' },
        { id: 'about', label: '关于', icon: 'bi-person', scrollNav: '1', href: '#services' },
        { id: 'services', label: '服务', icon: 'bi-briefcase', scrollNav: '2', href: '#services' },
        { id: 'work', label: '作品', icon: 'bi-columns', scrollNav: '3', href: '#work' },
        { id: 'contact', label: '联系', icon: 'bi-telephone', scrollNav: '4', href: '#contactus' }
      ]
    }
  },
  title: "侧边栏菜单内容",
  edit: EditComponent,
  save: SaveComponent
})

function EditComponent(props) {
  // 更新单个菜单项的文本
  const updateMenuItemLabel = (itemId, newLabel) => {
    const updatedItems = props.attributes.menuItems.map(item => 
      item.id === itemId ? { ...item, label: newLabel } : item
    )
    props.setAttributes({ menuItems: updatedItems })
  }

  return (
    <ul className="main-menu">
      {props.attributes.menuItems.map(item => (
        <li key={item.id}>
          <a data-scroll-nav={item.scrollNav} href={item.href}>
            <span className="m-icon">
              <i className={item.icon}></i>
            </span>
            <RichText 
              value={item.label} 
              onChange={(newLabel) => updateMenuItemLabel(item.id, newLabel)} 
              placeholder="输入菜单文本"
            />
          </a>
        </li>
      ))}
    </ul>
  )
}

function SaveComponent(props) {
  return (
    <ul className="main-menu">
      {props.attributes.menuItems.map(item => (
        <li key={item.id}>
          <a data-scroll-nav={item.scrollNav} href={item.href}>
            <span className="m-icon">
              <i className={item.icon}></i>
            </span>
            <RichText.Content value={item.label} />
          </a>
        </li>
      ))}
    </ul>
  )
}

关键说明:

  • 使用数组存储每个菜单项的独立数据,确保每个RichText绑定唯一的文本字段。
  • 通过map循环渲染菜单,每个项的key用唯一id保证React渲染性能。
  • 更新函数通过map修改数组中对应项的文本,避免直接修改原数组(符合React状态更新的不可变原则)。
  • 保存组件使用RichText.Content渲染最终的文本内容,确保前端显示正确。

内容的提问来源于stack exchange,提问作者Amin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 15:00:53