我已经设法创建了一个WordPress定制的Gutenberg块,并且我已经创建了一个面板部分来存储我所有的块选项。
然而,我是一个非常新的反应,我已经设法在一起脚手架。我试图给这个select一个初始状态,并在更改时保存状态。
我知道我需要用withState做点什么,但是我不确定我能不能看到我的承诺失败了,是不是,但我不确定为什么。
// Block Options
const withInspectorControls = createHigherOrderComponent( ( BlockEdit ) => {
return (props) => {
const size = {size:"display-2"};
return (
<Fragment>
<BlockEdit { ...props } />
<InspectorControls>
<PanelBody title="Display Block Settings"
icon="welcome-widgets-menus"
initialOpen={ true }
>
<SelectControl
label="Display Size"
value={size}
options={[
{ label: 'Display 1', value: 'display-1' },
{ label: 'Display 2', value: 'display-2' },
{ label: 'Display 3', value: 'display-3' },
{ label: 'Display 4', value: 'display-4' },
]}
onChange={ ( size ) => { setState( { size:size } ) } }
/>
</PanelBody>
</InspectorControls>
</Fragment>
);
};
}, "withInspectorControl" );
wp.hooks.addFilter( 'editor.BlockEdit', 'display-heading/with-inspector-controls', withInspectorControls );发布于 2019-04-13 01:14:25
你在正确的轨道上。正如你已经提到的,你真的只需要添加withState HOC。这可能如下所示:
// 1. add the withState import
import { withState } from '@wordpress/compose';
// 2. wrap your SelectControl with the withState HOC
const MySelectControl = withState( {
// this is your state, in this case display-2 would be the default
size: 'display-2',
} )( ( { size, setState } ) => (
<SelectControl
label="Size"
value={ size }
options={ [
{ label: 'Display 1', value: 'display-1' },
{ label: 'Display 2', value: 'display-2' },
{ label: 'Display 3', value: 'display-3' },
{ label: 'Display 4', value: 'display-4' },
] }
onChange={ ( size ) => { setState( { size } ) } }
/>
) );
// Block Options
const withInspectorControls = createHigherOrderComponent( ( BlockEdit ) => {
return (props) => {
return (
<Fragment>
<BlockEdit { ...props } />
<InspectorControls>
<PanelBody title="Display Block Settings"
icon="welcome-widgets-menus"
initialOpen={ true }
>
// 3. now you can add your component in your panel
<MySelectControl />
</PanelBody>
</InspectorControls>
</Fragment>
);
};
}, "withInspectorControl" );
wp.hooks.addFilter( 'editor.BlockEdit', 'display-heading/with-inspector-controls', withInspectorControls );反应高阶组件在一开始可能真的会让人感到困惑。但是,如果您熟悉OOP范式,则可以将它们视为composition模式。对于Gutenberg开发来说,最重要的事情是他们总是返回一个新的组件。这就是为什么我能够像这个<MySelectControl />一样使用它。
https://stackoverflow.com/questions/55655594
复制相似问题