我使用以下代码在Gutenberg提要栏中添加一个自定义选项。其可见并保存复选框值有效。
但是:如果我单击复选框控件,它上没有任何可见的更改。如果它没有被检查,而我想检查它,它就不会被检查。“The”;“更新”-按钮变为活动状态,我看到它后面有复选框。
为什么?
import { CheckboxControl } from \'@wordpress/components\';
import { dispatch, select } from \'@wordpress/data\';
import { PluginDocumentSettingPanel } from \'@wordpress/edit-post\';
import { Component } from \'@wordpress/element\';
import { __ } from \'@wordpress/i18n\';
export default class Sidebar extends Component {
render() {
const meta = select( \'core/editor\' ).getEditedPostAttribute( \'meta\' );
const toggleState = meta[\'code\'];
return (
<PluginDocumentSettingPanel
name="code"
title={ __( \'Display Settings\', \'myplugin\' ) }
>
<CheckboxControl
checked={ toggleState }
help={ __( \'My help.\', \'myplugin\' ) }
label={ __( \'My Label\', \'myplugin\' ) }
onChange={ ( value ) => {
dispatch( \'core/editor\' ).editPost( {
meta: {
\'code\': value,
},
} );
} }
/>
</PluginDocumentSettingPanel>
);
}
}
最合适的回答,由SO网友:Thomas Zwirner 整理而成
Solution found:
const { __ } = wp.i18n;
const { useSelect, useDispatch } = wp.data;
const { PluginDocumentSettingPanel } = wp.editPost;
const { CheckboxControl, PanelRow } = wp.components;
const Sidebar = () => {
const { postMeta } = useSelect( ( select ) => {
return {
postMeta: select( \'core/editor\' ).getEditedPostAttribute( \'meta\' ),
};
} );
const { editPost } = useDispatch( \'core/editor\', [ postMeta.code ] );
return(
<PluginDocumentSettingPanel title={ __( \'Display Settings\', \'myplugin\') }>
<PanelRow>
<CheckboxControl
label={ __( \'My Label\', \'myplugin\' ) }
checked={ postMeta.code }
onChange={ ( value ) => editPost( { meta: { code: value } } ) }
/>
</PanelRow>
</PluginDocumentSettingPanel>
);
}
export default Sidebar;