2017-09-10 58 views
0

我創建一個通用的功能checkField我的形式,我希望能夠從國家提取(或任何JavaScript對象),我作爲參數傳遞變量別名ES6 destructuration

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? 
} 

回答

3

得到你需要使用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');

+0

非常漂亮,它完美的作品! – dbrrt

+0

@dbrrt - 歡迎:) –