微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

动态添加和保存文本字段 - WordPress Gutenberg

如何解决动态添加和保存文本字段 - WordPress Gutenberg

我遇到了一些没有记录的事情(至少我找不到答案)。

我想创建(理想情况下是静态的)“自定义块”,它会随着内部状态的变化(编辑时)而改变。我正在尝试创建这样的最小工作示例 (MWE):

  1. 创建块(比方说产品块)
  2. 显示一个 <select> 输入
  3. 如果您选择 <option>,比如说“Sale”,那么在 <select> 下方应该会出现新的 <input type="text">,它指定了销售前产品的成本
  4. 要么保存“所选选项”IFF“销售”被选中,然后保存“所选选项”和“销售前成本”

我已经完成了第 1 - 3 步,但无法进行第 4 步。我不知道如何保存该变量结构以及在“属性”部分中究竟要定义什么。

非常感谢任何帮助,主要是对创建 MWE 的贡献。

这是我目前所拥有的:

var el = wp.element.createElement;

wp.blocks.registerBlockType('simon/dynamic-product-block',{
   title: 'Dynamic Product Block',icon: 'cart',category: 'common',attributes: {
      type: {
         type: 'string'
      },title: {
         type: 'string'
      },optionalField: {
         type: 'string'
      },},edit: function(props) {
      function updateTitle(event) {
         props.setAttributes({
            title: event.target.value
         });
      }

      function updateType(event) {
         props.setAttributes({
            type: event.target.value
         });
      }

      function updateOptionalField(event) {
         props.setAttributes({
            optionalField: event.target.value
         });
      }

      var res_obj = el(
         'div',{
            className: 'product-block product-' + props.attributes.type
         },el(
            'select',{
               onChange: updateType,value: props.attributes.type,el("option",{value: "normal" },"normal"),{value: "sale" },"Sale"),{value: "great-offer" },"Great offer")
         ),el(
            'input',{
               type: 'text',placeholder: 'Enter product title here...',value: props.attributes.title,onChange: updateTitle,style: { width: '100%' }
            }
         )
      );

      if (props.attributes.type == 'sale') {
         res_obj.props.children.push(
            el(
               'input',{
                  type: 'text',placeholder: 'Enter optional field text...',value: props.attributes.optionalField,onChange: updateOptionalField,style: { width: '100%' }
               }
            )
         );
      }

      return res_obj;
   },save: function(props) {
      var to_save = el( 'div',el(
            'h4',null,props.attributes.title
         ),);

      // ADD FROM COST (updateOptionalField) IFF SALE WAS CHOSEN
      // !!!!!!!!!!!!!!!!!!!!
      // RETURNS ERROR "to_save.props.children.push is not a function"
      // !!!!!!!!!!!!!!!!!!!!
      // if (props.attributes.type == 'sale') {
      //    to_save.props.children.push(
      //       el(
      //          'h5',//          { className: 'update-optional-field' },//          props.attributes.updateOptionalField
      //       )
      //    );
      // }

      return to_save;
   }
});

我发现的最相关的问题是:Create dynamic gutenberg TextControl components 但它没有解决

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。