【发布时间】:2018-07-31 09:52:05
【问题描述】:
我正在为 WordPress 编写一个古腾堡块插件,但我无法理解新的 ESNext 语法。我有一个带有键:值配对的字段列表。这是我正在使用的代码:
{
...
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 函数?
【问题讨论】:
-
试试
onChange={( name ) => setAttributes({ [name]: attributes[name] })} -
@dfsq 没用。我也试过你的代码,但是用
field_key而不是name,这也不起作用。 -
错误。应该是
onChange={( name ) => setAttributes({ [name]: fields[name] })}。 -
差不多,但不完全。我得到了它:
onChange={( v ) => setAttributes({ [field_key]: v })},但现在我遇到的问题是它只更新最后一个字段。
标签: javascript wordpress ecmascript-next wordpress-gutenberg