1

我正在尝试创建一个自定义 WordPress Gutenberg 块,其中包含多个通过 Rest API 提取的分类术语复选框。我可以用 SelectControl 做到这一点。使用 SelectControl,您只需将 multiple 设置为 true。我不相信 CheckboxControl 有这个选项。我想在 InspectorControls 中执行此操作。

4

3 回答 3

1

这是一个在 InspectorControls 中显示多个 CheckboxControls 的示例。在此示例中,我假设您将 API 响应与分类术语保存在taxs变量中,该变量是一个具有 key = tax ID 和 value = boolean(启用/禁用)的对象。

var el = wp.element.createElement;

blocks.registerBlockType('my/block', {

  // Other properties likt title, icon...

  attributes: {
    // No source, so saved in comment
    taxs: {
      type: "object"
    }
  },

  edit: function(props) {

    var taxs = props.attributes.taxs;

    // Don't mutate the original object but make a copy of it and mutate that one
    function onTaxCheckChange(newValue) {
      var copy = Object.assign({}, taxs);
      copy[this] = newValue;
      props.setAttributes({taxs: copy});
    }

    var checkboxes = Object.keys(taxs).map(function(taxId) {
      return el(components.CheckboxControl, {
        onChange: onTaxCheckChange.bind(taxId),
        label: taxId,
        checked: taxs[taxId]
      });
    });

    return el(wp.element.Fragment, null,
      // InspectorControls elements
      el(wp.editor.InspectorControls, null,
        el('div', null, checkboxes)
      ),
      // Block editor elements, can be anything...
      el('p', null, 'My block'));
  }
});
于 2019-12-06T10:08:12.313 回答
0

When you want to render elements in a loop, you have to set their states because it is object oriented. Their states values have to be merged with attributes values.

You should use js's map instead of jquery's each and work on a copy of your attributes value.

I don't know how to use apiFetch, so I give you a post_array exemple instead. Maybe you can use {withSelect}.

const posts_array = [{name: 'post_name', slug: 'post_slug'},{name: 'post_name', slug: 'post_slug'}]
const tracks = ('tracks' in attributes) ? attributes.tracks: new Object
const YourCheckBoxes = withState({
    checked_obj: Object.assign(new Object, tracks)
})( ( { checked_obj , setState } ) => (
    <ul>
    {   
        posts_array.map((v) => (
             <li><CheckboxControl
                className="check_items"
                label={v.name}
                checked={checked_obj[v.slug]}
                onChange={ ( check ) => {
                    check ? checked_obj[v.slug] = true : delete checked_obj[v.slug]
                    setAttributes({tracks : checked_obj}) 
                    setState({checked_obj})
                } }
            /></li>
        ) )
    }
    </ul>
) )

Then, you can call YourCheckBoxes in InspectorControls

<InspectorControls>
    <YourCheckBoxes />
</InspectorControls>
于 2019-11-05T14:31:11.953 回答
-1

要拥有多个复选框,您将需要多个 CheckboxControl。有关其选项,请参阅CheckboxControl 的文档。

于 2019-04-12T14:43:56.030 回答