我正在为 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
函数?