我正在使用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.addFilter
或customClassName
。它将导致重复。
答案 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'
);