如何在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
相关产品推荐
相关产品推荐

