如何将密钥传递给ESNext中的函数?

时间:2018-07-31 09:52:06

标签: javascript wordpress ecmascript-next wordpress-gutenberg

我正在为WordPress开发一个gutenberg块插件,但是我无法将自己的头围绕着新的ESNext语法。我有一个带有key:value配对的字段列表。这是我正在运行的代码:

{
  ...
  edit: function( { className, attributes, setAttributes } ) {
    return (
      <div className={ className }>
        <label className="field">
          <span className="field__label">Name</span>
          <PlainText
            className="field__input"
            id="email"
            value={ attributes.name }
            onChange={ ( name ) => setAttributes( { name } ) }
          />
        </label>
        <label className="field">
          <span className="field__label">Email</span>
          <PlainText
            className="field__input"
            id="email"
            value={ attributes.email }
            onChange={ ( email ) => setAttributes( { email } ) }
          />
        </label>
      </div>
    );
  }
  ...
}

我希望这段代码重复性较低,并避免复制粘贴。这就是我走的距离:

{
  edit: function( { className, attributes, setAttributes } ) {
    var fields = {
      name:    'Name',
      email:   'Email',
      phone:   'Phone',
      website: 'Website',
    }
    var html = [];
    for ( var field_key in fields ) {
      var label = fields[ field_key ];
      html.push( (
        <label className="field" key={field_key}>
          <span className="field__label">{ label }</span>
          <PlainText
            className="field__input"
            id={field_key}
            value={ attributes[field_key] }
            onChange={ ( ??? ) => setAttributes( { ??? } ) }
          />
        </label>
      ) );
    }
    return (
      <div className={ className }>
        {html}
      </div>
    );
  },
}

如何将field_key变量传递到setAttributes函数中?

2 个答案:

答案 0 :(得分:2)

实际上不需要绑定handler的{​​{1}}函数。如果仅将箭头函数传递给field_key,它将绑定onChange,然后可以将其传递给field_key

setAttributes

我在Codepen上举了一个例子来说明这一点(反应示例,​​但同样适用于您的情况)。

答案 1 :(得分:0)

我找到了解决方案。到onChange被触发时,for loop已经完成,field_key引用了最后一个键“网站”。为了解决这个问题,我为处理程序函数创建了一个闭包,该闭包将对当前迭代内对field_key的引用锁定。

const handler = (setter, key) => value => setter( { [key]: value } );
{
  ...
  edit: function( { className, attributes, setAttributes } ) {
    let fields = {
      name:    'Name',
      email:   'Email',
      phone:   'Phone',
      website: 'Website',
    }
    let html = [];
    for ( let field_key in fields ) {
      let label = fields[ field_key ];
      html.push( (
        <label className="field" key={field_key}>
          <span className="field__label">{ label }</span>
          <PlainText
            className="field__input"
            id={field_key}
            value={ attributes[field_key] }
            onChange={handler( setAttributes, field_key )}
          />
        </label>
      ) );
    }
    return (
      <div className={ className }>
        {html}
      </div>
    );
  },
  ...
}