Managing two editable fields in gutenberg
-
13-03-2021 - |
Pergunta
I'm building a gutenberg block plugin which takes two fields, a DOI name and a title. I can manage one successfully, but I'm not sure how to edit/save two at the same time. So far I have:
( function( blocks, components, i18n, element, _ ) {
const el = element.createElement;
const editable = blocks.Editable;
const __ = i18n.__;
blocks.registerBlockType( 'doib/doi', {
title: __( 'DOI', 'doib' ),
icon: 'id',
category: 'widgets',
attributes: {
doi: {
type: 'string',
},
title: {
type: 'string',
},
},
supports: {
html: false,
},
edit: function( props ) {
const focus = props.focus;
function onChangeDOI( updated ) {
props.setAttributes( { doi: updated } );
}
return (
el(
editable,
{
className: props.className,
value: props.attributes.doi,
placeholder: __( 'Enter DOI name. Takes the form of "10.1000/xyz123".' ),
onChange: onChangeDOI,
focus: focus,
onFocus: props.setFocus,
},
)
);
},
save: function( props ) {
return (
el( 'div', { className: props.className, dataDoi: props.attributes.doi },
props.attributes.doi,
)
);
},
} );
}(
window.wp.blocks,
window.wp.components,
window.wp.i18n,
window.wp.element
) );
And I'm not too sre how to proceed beyonf this point.
Solução
Editable
has been replaced with RichText
in 2.2.
Here's a example of two RichText components being edit/saved together:
const { __ } = wp.i18n;
const {
registerBlockType,
RichText,
} = wp.blocks;
registerBlockType( 'wtv/wtv', {
title: __( 'wtv', 'wtv' ),
icon: 'id',
category: 'widgets',
keywords: [ __( 'wtv' ), __( 'wtv' ), __( 'wtv' ) ],
attributes: {
doi: {
type: 'string',
selector: '.doi',
default: '',
},
title: {
type: 'string',
selector: '.title',
default: '',
},
},
edit( { attributes, setAttributes, className } ) {
const onChangeDOI = value => {
setAttributes( { doi: value } );
};
const onChangeTitle = value => {
setAttributes( { title: value } );
};
return (
<div className={ className } >
<RichText
tagname="div"
placeholder="Enter DOI name. Takes .."
value={ attributes.doi }
onChange={ onChangeDOI }
/>
<RichText
tagname="div"
placeholder="Title .."
value={ attributes.title }
onChange={ onChangeTitle }
/>
</div>
);
},
save: function( props ) {
return ( <div className={ props.className } >
<div className="doi">
{ props.attributes.doi }
</div>
<div className="title">
{ props.attributes.title }
</div>
</div> );
},
} );
I apologize my answer isn't in es5, but its so much easier in ESNext (highly recommend using @ahmadawais create-guten-block for the tooling)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a wordpress.stackexchange