【问题标题】:WordPress Gutenberg RichText not displaying HTMLWordPress Gutenberg RichText 不显示 HTML
【发布时间】:2018-09-20 08:58:14
【问题描述】:

如下面的代码sn-p所示,我试图将HTML或JSX附加到RichText内容中是徒劳的。

const { registerBlockType } = wp.blocks;
const { RichText } = wp.editor;

registerBlockType( /* ... */, {
    // ...

    attributes: {
        content: {
            type: 'array',
            source: 'children',
            selector: 'p',
            default: [],
        },
    },

    edit( { className, attributes, setAttributes } ) {

        const updateContentWithString = ( content ) => {

            setAttributes( { content: content.concat( 'test' ) } );

        }

        const updateContentWithHTML = ( content ) => {

            setAttributes( { content: content.concat( <Button isDefault >Test Button</Button> ) } );

        }

        return (
            <RichText
                tagName="p"
                className={ className }
                value={ attributes.content }
                onChange={ updateContentWithString } // updateContentWithString works fine BUT updateContentWithHTML doesn't work at all
            />
        );
    },

    save( { attributes } ) {
        return <RichText.Content tagName="p" value={ attributes.content } />;
    }
} );

我想知道为什么 updateContentWithString() 工作正常但 updateContentWithHTML() 根本不起作用。

请指导我。

谢谢

【问题讨论】:

    标签: wordpress reactjs wordpress-gutenberg


    【解决方案1】:

    试试

    setAttributes( { content: content.concat( '<Button isDefault >Test Button</Button> )' } );
    

    在 JSX 中,&lt;Button/&gt; 将被预处理/转换为 React.createElement 以创建组件。

    注意:在 JSX 中 &lt;Button/&gt;&lt;button/&gt; 不同(组件与 html)

    更新:

    以上仅与 react/JSX 相关。 我不知道或使用过古腾堡(还),但根据this html 元素应该作为对象传递,而不是 html 源。可能您应该使用wp.element.createElementRichText 甚至定义/使用自己的自定义块类型。

    在 Gutenberg 中搜索编辑/更新/创建 html(元素)的方法。

    【讨论】:

    • 感谢@xadm 的回复,但setAttributes( { content: content.concat( '&lt;Button isDefault &gt;Test Button&lt;/Button&gt;' ) } ); 只是将字符串&lt;Button isDefault &gt;Test Button&lt;/Button&gt; 添加到富文本中,而不是添加按钮。
    猜你喜欢
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 2019-05-12
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    • 2020-01-13
    • 1970-01-01
    相关资源
    最近更新 更多