自定义古腾堡块内特定 Richtext 组件的工具栏按钮

问题描述 投票:0回答:1

我有一个自定义的 Gutenberg 块,里面有多个 RichText 组件。我需要为不同的 RichText 组件显示特定的 ToolbarButtons,在与 formatTypes 的本机方法类似的 UX 中,例如:

allowedFormats={['core/italic']}

将显示 RichText 元素的斜体控件。我不希望注册格式类型,因为这些控件会保存块属性而不是调整富文本格式。它引导我进行了一些实验,在那里我有一个几乎可行的概念,在这里伪代码:

edit : () => {

    const [isRichText1Focus,setIsRichText1Focus] = useState(false)
    const [isRichText2Focus,setIsRichText2Focus] = useState(false)

    return (
        
        <>
        
            {isRichText1Focus && (

                <BlockControls>
                    <ToolbarGroup>
                        <ToolbarButton
                            icon="test"
                            title="Title"
                            onClick={ () => {
                                //Change a block attribute 
                            } }
                        />
                    </ToolbarGroup>
                </BlockControls>

            )}

            {isRichText2Focus && (

                <BlockControls>
                    <ToolbarGroup>
                        <ToolbarButton
                            icon="test 2"
                            title="Title 2"
                            onClick={ () => {
                                //Change another block attribute 
                            } }
                        />
                    </ToolbarGroup>
                </BlockControls>

            )}

            <div className='blockName'>

                <RichText
                    onBlur={() => {
                        setIsRichText1Focus(false)
                    }}
                    ...//other params
                    unstableOnFocus={() => {
                        setIsRichText1Focus(true)
                    }}
                />

                <RichText
                    onBlur={() => {
                        setIsRichText2Focus(false)
                    }}
                    ...//other params
                    unstableOnFocus={() => {
                        setIsRichText2Focus(true)
                    }}
                />

            </div>
        </>

    ]) 

}

你可以看到我在这里的尝试是仅在 RichText 区域处于焦点时显示某些块控制按钮。但是,不可能获得同时覆盖工具栏本身的可靠“onBlur”,因此 RichText 组件上的 onBlur 是不合适的。 Gutenberg 中显然有一个可靠的焦点/模糊概念,因为 registerFormatType 和 formatTypes API 可以很好地处理这个问题。我可以用这种方法以某种方式复制它吗?还是这种方法太老套了,我应该完全采用不同的方法?使用本机工具栏而不是创建我自己的 UI 会很棒。

wordpress wordpress-gutenberg gutenberg-blocks
1个回答
0
投票

我会采取不同的方法,使用 InnerBlocksblock variations 通过创建自定义父子块。

父块就像一个包装块,只包含一个

InnerBlocks
设置,通过
template
存储自定义子块变体。这使您能够指定子块及其属性的初始状态。

Child 块包含一个

RichText
组件,其块属性定义了
Toolbar
内容以通过块变体更改。这样,当 RichText 被选中时,正确的工具栏被呈现;焦点仍然在块级别,不需要
setState()
或潜在的坏
setState()
调用。

当你使用块控件时,我会在块级别实现它们。如果您还研究了如何将块控件添加到现有的块过滤器,例如

wp.hooks.addFilter('editor.BlockEdit', ...)
,它可能会帮助您找到解决问题的不同方法。

© www.soinside.com 2019 - 2024. All rights reserved.