我有一个自定义古腾堡积木,它使用两个自定义组件。每个组件在Inspector控制面板中都有一个切换。这只是一个简化的场景,实际上,将有两个以上的组件。
// My GB block
import PreTitle from \'../components/PreTitle\';
import Title from \'../components/Title\';
const { registerBlockType } = wp.blocks;
const blockConfig = {
title: \'My Block\',
category: \'my-blocks\',
attributes: {
// Some attributes
},
edit: ( props ) => {
return (
<div className={`controls`}>
<PreTitle { ...props } />
<Title { ...props } />
</div>
);
},
save: ({attributes: { preTitleContent, TitleContent }}) => {
return(
<div className={`controls`}>
<PreTitle.Content { ...props } />
<Title.Content { ...props } />
</div>
);
}
};
export const headings = registerBlockType(
`cv-wp-lib-gutenberg-blocks/headings`,
blockConfig
);
我的标题组件:
const Title = ( props ) => {
// ... some code
return (
<>
<InspectorControls>
<PanelBody>
<ToggleControl
label={ __(`Toggle title`, `cv-wp-lib-gutenberg-blocks`) }
checked={ showTitle }
onChange={ onChangeToggleField }
/>
</PanelBody>
</InspectorControls>
// ... some JSX
</>
);
};
我的字幕组件:
const PreTitle = ( props ) => {
// ... some code
return (
<>
<InspectorControls>
<PanelBody>
<ToggleControl
label={ __(`Toggle preTitle`, `cv-wp-lib-gutenberg-blocks`) }
checked={ showPreTitle }
onChange={ onChangeToggleField }
/>
</PanelBody>
</InspectorControls>
// ... some JSX
</>
);
};
Question: 有没有办法让组件共享同一个面板?
最合适的回答,由SO网友:Jonas Merhej 整理而成
您有两种选择:
只需编写一个InspectorControl并将其放入主组件/块中,然后从标题和PreTitle js文件中删除InputorControl。不要忘记更改onChange函数名“onChangeToggleField”,因为它们共享相同的函数名。无论您现在更改什么道具,现在都应该传递给标题和字幕
// My GB block
import PreTitle from \'../components/PreTitle\';
import Title from \'../components/Title\';
const { registerBlockType } = wp.blocks;
const blockConfig = {
title: \'My Block\',
category: \'my-blocks\',
attributes: {
// Some attributes
},
edit: ( props ) => {
return (
<>
<InspectorControls>
<PanelBody>
<ToggleControl
label={ __(`Toggle title`, `cv-wp-lib-gutenberg-blocks`) }
checked={ showTitle }
onChange={ onChangeToggleFieldTitle }
/>
<ToggleControl
label={ __(`Toggle preTitle`, `cv-wp-lib-gutenberg-
blocks`) }
checked={ showPreTitle }
onChange={ onChangeToggleFieldPreTitle }
/>
</PanelBody>
</InspectorControls>
<div className={`controls`}>
<PreTitle { ...props } />
<Title { ...props } />
</div>
</>
);
},
save: ({attributes: { preTitleContent, TitleContent }}) => {
return(
<div className={`controls`}>
<PreTitle.Content { ...props } />
<Title.Content { ...props } />
</div>
);
}
};
export const headings = registerBlockType(
`cv-wp-lib-gutenberg-blocks/headings`,
blockConfig
);
编写一个额外的组件(例如MyGbBlockInspector.js)并将其导入到块中。
// My GB block
import PreTitle from \'../components/PreTitle\';
import Title from \'../components/Title\';
import MyGbBlockInspector from \'../components/MyGbBlockInspector\';
我更喜欢选项2,尽管问题是,标题和PreTitle现在不再是全局的,不能在不重写其InspectorControls函数的情况下简单地用于其他块。