我是react和Gutenberg开发的新手,我正在尝试在文档侧栏中添加一些字段。
虽然我成功地将meta保存为单个值,但我正在努力找到将字段保存为数组的方法。
JS公司
import { __ } from \'@wordpress/i18n\';
import { compose } from \'@wordpress/compose\';
import { registerPlugin } from \'@wordpress/plugins\';
import { PluginDocumentSettingPanel } from \'@wordpress/edit-post\';
import { TextControl } from "@wordpress/components";
import { select, withSelect, withDispatch } from \'@wordpress/data\';
import { Fragment } from \'@wordpress/element\';
function TestControl( { newValue, updateMeta } ) {
return (
<Fragment>
<TextControl
label={ __( \'Field One\', \'test\' ) }
value={ newValue.one }
onChange={ ( value ) => updateMeta( value ) }
/>
<TextControl
label={ __( \'Field Two\', \'test\' ) }
value={ newValue.two }
onChange={ ( value ) => updateMeta( value ) }
/>
</Fragment>
);
}
const FieldsTestControl = compose( [
withSelect( () => {
return {
newValue: select( \'core/editor\' ).getEditedPostAttribute( \'meta\' )._metakey,
};
} ),
withDispatch( ( dispatch ) => ( {
updateMeta( value ) {
dispatch( \'core/editor\' ).editPost(
{ meta: { _metakey:{
\'one\': value.one,
\'two\': value.two,
} } }
);
},
} ) ),
] )( TestControl );
const TestPanel = () => {
return (
<PluginDocumentSettingPanel
name="test"
title="Test"
className="test"
>
<FieldsTestControl />
</PluginDocumentSettingPanel>
);
};
registerPlugin( \'test-panel\', {
render: TestPanel,
icon: \'\',
} );
PHP
register_post_meta( \'post\', \'_metakey\', [
\'type\' => \'object\',
\'single\' => true,
\'auth_callback\' => \'__return_true\',
\'show_in_rest\' => [
\'schema\' => [
\'type\' => \'object\',
\'properties\' => [
\'one\' => [
\'type\' => \'string\',
],
\'two\' => [
\'type\' => \'string\',
],
],
],
],
]);
最合适的回答,由SO网友:Sally CJ 整理而成
代码中的问题是updateMeta()
功能value
是一个字符串(这是您在文本字段中键入或输入的内容),因此您不能执行value.one
或value.two
.
因此,请尝试使用新的函数参数,即prop
正在更新的元数据中的当前属性:
updateMeta( value, prop ) { // the \'prop\' is the current property to be updated
let meta = select( \'core/editor\' ).getEditedPostAttribute( \'meta\' )._metakey;
// Make sure all props are defined. (and merge with current metadata values)
meta = {
one: \'\',
two: \'\',
...meta,
};
// Then update the current property.
meta[ prop ] = value;
dispatch( \'core/editor\' ).editPost({ meta: { _metakey: meta } });
}
然后在
TextControl
\'s
onChange
属性:
使用updateMeta( value, \'one\' )
对于Field One
领域
使用updateMeta( value, \'two\' )
对于Field Two
领域
您不必使用与我上面给出的完全相同的代码,但这是一个工作(已测试)的示例。快乐编码!:)