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

如何在WordPress Gutenberg编辑器侧边栏自定义区块中为ColorPalette添加模板颜色

实现步骤

你可以直接通过Gutenberg提供的useSetting钩子获取主题预设的模板颜色,再传入原生ColorPalette组件即可,完全不需要依赖PanelColorSettings,可以直接嵌入你现有的PanelBody中。

1. 导入依赖

首先引入需要的核心模块:

import { PanelBody, TextControl, ColorPalette } from '@wordpress/components';
import { useSetting } from '@wordpress/block-editor';

2. 声明属性

在区块的attributes配置中新增边框颜色字段:

attributes: {
  // 你原有的其他属性
  inputPlaceholder: {
    type: 'string',
    default: ''
  },
  // 新增边框颜色属性
  borderColor: {
    type: 'string',
    default: ''
  }
}

3. 组件中集成

在编辑函数的PanelBody中直接嵌入ColorPalette:

edit: ( { attributes, setAttributes } ) => {
  // 获取主题预设的全局颜色模板
  const themeColorPalette = useSetting( 'color.palette' );
  const { inputPlaceholder, borderColor } = attributes;

  return (
    <PanelBody title={ '区块配置' } initialOpen={ true }>
      {/* 你原有的其他配置项 */}
      <TextControl
        label={ '输入框占位文本' }
        value={ inputPlaceholder }
        onChange={ (val) => setAttributes( { inputPlaceholder: val } ) }
      />
      {/* 新增边框颜色选择器 */}
      <p style={{ marginBottom: '8px', fontWeight: 500 }}>*输入边框颜色*</p>
      <ColorPalette
        colors={ themeColorPalette } // 传入主题预设色
        value={ borderColor }
        onChange={ (newColor) => setAttributes( { borderColor: newColor } ) }
        disableCustomColors={ false } // 设为true可禁用用户自定义十六进制颜色
      />
    </PanelBody>
  );
}

效果参考

参考示意图


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 18:18:03