Я пытаюсь создать собственный блок в Гутенберге, который включает загрузку изображения. У меня проблема в том, что render
в MediaUpload
не работает. Думаю, что-то упускаю, но не могу найти.
Всякий раз, когда я пытаюсь поместить элемент MediaUpload
в блок, он оказывается пустым. В приведенном ниже коде, если вы проверите его, вы увидите <div class = "image-test">
, но внутри него ничего не будет.
Я попытался упростить приведенный ниже код, чтобы убедиться, что ему ничего не мешает, но у меня это все равно не сработало.
Это код block.js
:
const { registerBlockType } = wp.blocks;
const { MediaUpload, MediaUploadCheck } = wp.editor;
const { Button } = wp.components;
registerBlockType( 'custom/image-test', {
title: 'Image Test',
icon: 'warning',
category: 'custom-blocks',
edit( { attributes, className, setAttributes } ) {
return (
<div className = "image-test">
<MediaUploadCheck>
<MediaUpload
onSelect = { media => console.info( media.length ) }
render = { ({ open }) => (
<Button onClick = { open }>
Open Media Library
</Button>
)}
/>
</MediaUploadCheck>
</div>
);
},
save( { attributes } ) {
return (
<div class = "image-test">
<p>Image Test</p>
</div>
);
},
} );
Здесь я объявляю блок в функциях:
function image_test_block(){
wp_register_script(
'image-test-script', // name of script
get_template_directory_uri() . '/js/block-image-test.js', // path to script
array( 'wp-blocks', 'wp-element', 'wp-editor', 'wp-components' ) // dependencies
);
register_block_type('custom/image-test', array(
'editor_script' => 'image-test-script'
) );
}
add_action( 'init', 'image_test_block', 10, 0 );
Во-первых, насколько я помню, MediaUploadCheck не был официальным компонентом WP. Вот билет предложения
Используйте инструменты блочной разработки, такие как создать блок Guten, чтобы не беспокоиться о настройке. Я не уверен насчет постановки вашего скрипта в очередь, скорее всего, вы добавляете свои активы через неправильный хук.
Это рабочая карта рецептов с компонентом mediaUpload в ней.
const { __, setLocaleData } = wp.i18n;
const {
registerBlockType,
} = wp.blocks;
const {
RichText,
MediaUpload,
} = wp.editor;
const { Button } = wp.components;
setLocaleData( window.gutenberg_examples_05_esnext.localeData, 'gutenberg-examples' );
registerBlockType( 'gutenberg-examples/example-05-recipe-card-esnext', {
title: __( 'Example: Recipe Card (esnext)', 'gutenberg-examples' ),
icon: 'index-card',
category: 'layout',
attributes: {
title: {
type: 'array',
source: 'children',
selector: 'h2',
},
mediaID: {
type: 'number',
},
mediaURL: {
type: 'string',
source: 'attribute',
selector: 'img',
attribute: 'src',
},
ingredients: {
type: 'array',
source: 'children',
selector: '.ingredients',
},
instructions: {
type: 'array',
source: 'children',
selector: '.steps',
},
},
edit: ( props ) => {
const {
className,
attributes: {
title,
mediaID,
mediaURL,
ingredients,
instructions,
},
setAttributes,
} = props;
const onChangeTitle = ( value ) => {
setAttributes( { title: value } );
};
const onSelectImage = ( media ) => {
setAttributes( {
mediaURL: media.url,
mediaID: media.id,
} );
};
const onChangeIngredients = ( value ) => {
setAttributes( { ingredients: value } );
};
const onChangeInstructions = ( value ) => {
setAttributes( { instructions: value } );
};
return (
<div className = { className }>
<RichText
tagName = "h2"
placeholder = { __( 'Write Recipe title…', 'gutenberg-examples' ) }
value = { title }
onChange = { onChangeTitle }
/>
<div className = "recipe-image">
<MediaUpload
onSelect = { onSelectImage }
allowedTypes = "image"
value = { mediaID }
render = { ( { open } ) => (
<Button className = { mediaID ? 'image-button' : 'button button-large' } onClick = { open }>
{ ! mediaID ? __( 'Upload Image', 'gutenberg-examples' ) : <img src = { mediaURL } alt = { __( 'Upload Recipe Image', 'gutenberg-examples' ) } /> }
</Button>
) }
/>
</div>
<h3>{ __( 'Ingredients', 'gutenberg-examples' ) }</h3>
<RichText
tagName = "ul"
multiline = "li"
placeholder = { __( 'Write a list of ingredients…', 'gutenberg-examples' ) }
value = { ingredients }
onChange = { onChangeIngredients }
className = "ingredients"
/>
<h3>{ __( 'Instructions', 'gutenberg-examples' ) }</h3>
<RichText
tagName = "div"
multiline = "p"
className = "steps"
placeholder = { __( 'Write the instructions…', 'gutenberg-examples' ) }
value = { instructions }
onChange = { onChangeInstructions }
/>
</div>
);
},
save: ( props ) => {
const {
className,
attributes: {
title,
mediaURL,
ingredients,
instructions,
},
} = props;
return (
<div className = { className }>
<RichText.Content tagName = "h2" value = { title } />
{
mediaURL && (
<img className = "recipe-image" src = { mediaURL } alt = { __( 'Recipe Image', 'gutenberg-examples' ) } />
)
}
<RichText.Content tagName = "h2" className = "ingredients" value = { ingredients } />
<RichText.Content tagName = "div" className = "steps" value = { instructions } />
</div>
);
},
} );
В вашем компоненте mediaUload отсутствует идентификатор носителя, обязательная функция onSelect, а также вы выводите значение в консоли поиска.