我正在尝试使用<FocalPointPicker />
在里面<PluginDocumentSettingPanel />
几乎所有的东西都正常工作,但我在创建新帖子时遇到了麻烦。我收到以下警告:
警告:已收到value
属性
据我所知,这是因为post meta尚未创建。我通过添加update_post_meta
在后期创建期间。但我认为应该有一个更好的解决方案使用纯反应。
这是我的代码:
// in init.php
add_action(\'init\',\'register_my_post_meta\');
function register_my_post_meta() {
$args_img = array(
\'type\' => \'object\',
\'single\' => true,
\'show_in_rest\' => array(
\'schema\' => array(
\'type\' => \'object\',
\'properties\' => array(
\'url\' => array(
\'type\' => \'url\',
),
\'width\' => array(
\'type\' => \'number\',
),
\'height\' => array(
\'type\' => \'number\',
),
\'id\' => array(
\'type\' => \'number\',
),
),
),
),
);
$args_focal = array(
\'type\' => \'object\',
\'single\' => true,
\'show_in_rest\' => array(
\'schema\' => array(
\'type\' => \'object\',
\'properties\' => array(
\'x\' => array(
\'type\' => \'number\',
),
\'y\' => array(
\'type\' => \'number\',
),
),
),
),
);
register_post_meta( \'\', \'img\', $args_img );
register_post_meta( \'\', \'focalPoint\', $args_focal );
}
// in index.js
const { registerPlugin } = wp.plugins;
const { PluginDocumentSettingPanel } = wp.editPost;
const { withSelect, withDispatch } = wp.data;
const { MediaUpload, MediaUploadCheck } = wp.blockEditor;
const { Button, FocalPointPicker } = wp.components;
let PhotoControl = ({img, focalPoint, handleImgChange, handleFocalChange}) =>(
<MediaUploadCheck>
{!!img["url"] &&
<FocalPointPicker
url={ img["url"] }
value={ focalPoint }
onChange={ focalPoint => handleFocalChange(focalPoint)}
/>
}
{!img["url"] &&
<MediaUpload
title="My Image"
onSelect={
img => handleImgChange(img)
}
allowedTypes={[\'image\']}
value={ img }
render= { ( { open } ) => (
<Button
id={\'image-upload\'}
onClick={open}>
{ ! img["url"] && "upload image" }
</Button>
) }
/>
}
</MediaUploadCheck
);
PhotoControl = withSelect(
(select) => {
return {
img: select(\'core/editor\').getEditedPostAttribute(\'meta\')[\'img\'],
focalPoint: select(\'core/editor\').getEditedPostAttribute(\'meta\')[\'focalPoint\']
}
}
)(PhotoControl);
PhotoControl = withDispatch(
(dispatch) => {
return {
handleImgChange: (value) => {
dispatch(\'core/editor\').editPost({ meta: { img:{
"url": value.url,
"width": value.width,
"height": value.height,
"id": value.id
} })
}
handleFocalChange: (value) => {
dispatch(\'core/editor\').editPost({ meta: { focalPoint: value } })
}
}
}
)(PhotoControl);
const PluginWithFocalpoint = () => {
return(
<PluginDocumentSettingPanel>
<PhotoControl />
</PluginDocumentSettingPanel>
);
}
registerPlugin( \'plugin-with-focalpoint\', { render: PluginWithFocalpoint, icon: \' \' } );
这里是我的临时解决方案:
// in init.php
function create_meta_for_new_posts($post_id, $post, $update) {
if (empty(get_post_meta( $post_id, \'focalPoint\' ))) {
update_post_meta( $post_id, \'focalPoint\', array("x"=>0.5,"y"=>0.5) );
}
}
add_action( \'wp_insert_post\', \'create_meta_for_new_posts\', 10, 3 );