我正在为表单创建通用函数checkField
,并且希望能够从状态(或任何JavaScript对象)中提取作为参数传递的变量
checkField(fieldname) {
const {
validityFieldObj,
fieldname
} = this.state
// Would be equivalent to `this.state[fieldname]`
// But I can't get fieldname from this.state destructuration,
// as it as already been delcared in the parameter.
// Any alternative to this issue?
}
最佳答案
要获取字段名称,您需要使用destructuring with computed property name,并将结果分配给变量:
const state = {
validityFieldObj: {},
abc: 3
};
function checkField(fieldname) {
const {
validityFieldObj,
[fieldname]: value
} = state;
console.log(value);
}
checkField('abc');
如果需要提取属性名称
fieldName
,则可以使用别名:const state = {
validityFieldObj: {},
fieldname: 'abc'
};
function checkField(fieldname) {
const {
validityFieldObj,
fieldname: nameOfField
} = state;
console.log(nameOfField);
}
checkField('abc');
关于javascript - 别名ES6破坏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46145470/