Gutenberg / React将动态属性传递给过滤器功能

时间:2019-01-07 19:23:18

标签: reactjs wordpress-gutenberg

我正在使用Gutenberg block filters尝试在编辑器中将动态类名添加到块的包装器组件中。

registerBlockType( name, {

    title: __( 'My Block' ),

    parent: [ 'myplugin/myblock' ],

    category: 'common',

    attributes: attributes,


    edit( { attributes, setAttributes, className } ) {      

        const { someName } = attributes;

        /* how can I pass someName from here to customClassName? */

        return (
            /* render something */
        );
    },

    save( { attributes } ) {

        const { someName } = attributes;

        /* how can I pass someName from here to customClassName? */

        return (
            /* render something */
        );
    },
});



const customClassName = createHigherOrderComponent( ( BlockListBlock ) => {
    return ( props ) => {
        return <BlockListBlock { ...props } className={ someName } />;
    };
}, 'customClassName' );

wp.hooks.addFilter( 'editor.BlockListBlock', 'myplugin/myblock', customClassName );

问题:常量someName中的customClassName未定义。

如何将someName从编辑或保存功能传递给常数customClassName?将在wp.hooks.addFilter中使用。

注意:我不能直接在编辑或保存功能中添加wp.hooks.addFiltercustomClassName。它将导致重复。

3 个答案:

答案 0 :(得分:3)

这里是简单的错字:)

return <BlockListBlock className={ props.someName } { ...props } />;
  

注意 :如果出现以下情况,我想使道具能够覆盖className   需要。

另一种解决方案:

return <BlockListBlock { ...props } className={ [props.someName, props.className] } />;

答案 1 :(得分:2)

如果someName是属性,则可以按以下方式访问它

className={props.attributes.someName}

答案 2 :(得分:1)

实际上,我想您在提问中犯了一个错误。当然,someName对象中存在attributes值,它是props对象的一部分,因此您可以像下面这样简单地访问它:

const customClassName = createHigherOrderComponent(( BlockListBlock ) => {
  return ( props ) => {
    return <BlockListBlock {...props} className={props.attributes.someName} />;
  };
}, 'customClassName');

我想说的另一件事是,您的代码不需要花括号和return函数:

const customClassName = createHigherOrderComponent(
  BlockListBlock => props => (
    <BlockListBlock {...props} className={props.attributes.someName} />
  ),
  'customClassName'
);