我尝试构建自己的自定义图库gutenberg块,如这里所示,以便更好地熟悉块结构。将所有代码放入单个文件可以正常工作,但当我试图在edit.js和save.js中将其拆分时,当尝试向其添加图像时,它会返回此错误:"Uncaught : setAttributes不是函数“。
我没能解决这事,有什么问题吗?
block.json中的属性
"attributes": {
"images" : {
"type": "array"
}
},edit.js
/**
* Retrieves the translation of text.
*
* @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-i18n/
*/
import { __ } from '@wordpress/i18n';
/**
* React hook that is used to mark the block wrapper element.
* It provides all the necessary props like the class name.
*
* @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-block-editor/#useblockprops
*/
import {
useBlockProps,
MediaUpload
} from '@wordpress/block-editor';
import {
Button
} from '@wordpress/components';
//import {registerBlockType} from "@wordpress/blocks";
/**
* Lets webpack process CSS, SASS or SCSS files referenced in JavaScript files.
* Those files can contain any CSS code that gets applied to the editor.
*
* @see https://www.npmjs.com/package/@wordpress/scripts#using-css
*/
import './editor.scss';
/**
* The edit function describes the structure of your block in the context of the
* editor. This represents what the editor will render when the block is used.
*
* @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#edit
*
* @return {WPElement} Element to render.
*/
export default function Edit(attributes, className, setAttributes) {
const blockProps = useBlockProps();
// Getting the images of the array
const {images = [] } = attributes;
// to remove image from gallery
const removeImage = (removeImage) => {
//filter images
const newImages = images.filter( (image) => {
// if current image is equal to removeImage, image will be returend
if(image.id != removeImage.id) {
return image;
}
});
//save new state
setAttributes({
images: newImages,
})
}
//Display the images
const displayImages = (images) => {
return (
//Loop through images
images.map((image) => {
return (
<div className="gallery-item-container">
<img className='gallery-item' src={image.url} key={ images.id } />
<div className='remove-item' onClick={() => removeImage(image)}><span class="dashicons dashicons-trash"></span></div>
<div className='caption-text'>{image.caption[0]}</div>
</div>
)
})
)
}
//JSX to return
return (
<>
<div {...blockProps}>
<div className='gallery-grid'>
{displayImages(images)}
</div>
<br/>
<MediaUpload
onSelect={(media) => setAttributes({
images: [...images,...media],
})
}
type="image"
multiple={true}
gallery={true}
value={images}
render={({open}) => (
<Button className="select-images-button is-button is-default is-large" onClick={open}>
Add images
</Button>
)}
/>
</div>
</>
);
}发布于 2023-02-24 18:38:55
你试过:
export default function Edit( { attributes, className, setAttributes } ) {Edit是react组件,react组件接收道具,因此Edit( props )更精确,因此示例中的{}
https://wordpress.stackexchange.com/questions/414163
复制相似问题