admin管理员组文章数量:1277509
I'd need to slightly modify the structure of the core/image
figcaption
component in the filtered save
function by adding a span
wrapper to the contents of the caption (I need another markup element for my frontend plans). I have worked a lot with the editor and done a lot of custom blocks, but I have struggled on exactly this task a couple of times. I believe it's some misconception of mine with React (as always). Everything works and I can console.log
all values at all stages successfully until the very moment when I try to re-inject my new JSX into props.children
. As soon as I uncomment this line I get a blank screen and React tells me Type error: children.props is undefined
.
This is my code for the filtered save
function of the extended core/image
block:
function customImageSave( element, blockType, attributes ) {
if ( ! restrictToBlocks.includes( blockType.name ) ) {
return element;
}
// Custom boolean attribute added to core image block
const { addSpan } = attributes;
const { children } = element.props;
// array with img and figcaption elements (maybe good idea to spread in new array?)
const innerElems = [ ...children.props.children ];
// image
const theImage = innerElems[0];
// figcaption
const theCaption = innerElems[1];
// only if figcaption is used at all (otherwise 'false')
if ( theCaption ) {
// get string value of figcaption content
let theValue = theCaption.props.value;
let theJSX;
// only if span needs to be added
if ( addSpan ) {
// check if figcaption is already wrapped in <span></span>
if ( ! theValue.includes( '<span>' ) ) {
// otherwise construct new JSX
theJSX = <figcaption><span>{theValue}</span></figcaption>;
}
} else {
// if no span should be added but figcaption already includes <span> wrapper, remove it
if ( theValue.includes( '<span>' ) ) {
theValue.replace( '<span>', '' );
theValue.replace( '</span>', '' );
// rebuild 'original' JSX without <span>
theJSX = <figcaption>{theValue}</figcaption>;
}
}
// new Array with unchanged img element and new figcaption element
const newChildren = [ theImage, theJSX ];
// try to inject it (fails)
element.props.children.props.children = newChildren;
return element;
}
return element;
}
addFilter( 'blocks.getSaveElement', 'vortac/custom-image-save', customImageSave );
Any help / advise really appreciated. Would it be better to post the whole code of the block (to test it?)
本文标签: Modify coreimage block by adding inner span to figcaption in save
版权声明:本文标题:Modify coreimage block by adding inner span to figcaption in save 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741257782a2367018.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论