我有一些非常基本的Typescript代码:
export const defaultListingFormValues = {
itemWeight: 1
}
有没有一种方法可以将默认值设置itemWeight
为有条件,该默认值取决于通过列表形式的下拉列表选择的项目类别?
喜欢的东西dress = 0.5, heels = 1, boots = 2, etc.
,这取决于选项被选中?
您可以将defaultListingFormValues
类别定义objects
为{ itemWeight: 1, dress: { itemWeight: 1 },... }
。
并将其与category
下拉菜单中的值一起使用,如下所示。在这里categoryFromDropDown保存category from dropdown
ie dress
。二手condition
所以如果category
没有那么定义它将返回default
值。
let defaultValue = defaultListingFormValues[categoryFromDropDown] ?
defaultListingFormValues[categoryFromDropDown].itemWeight :
defaultListingFormValues.itemWeight;
请在下面尝试。对于演示export
和import
陈述评论。
// export const defaultListingFormValues = {
const defaultListingFormValues = {
itemWeight: 1,
dress: {
itemWeight: 0.5
},
heels: {
itemWeight: 1
},
boots: {
itemWeight: 2
}
}
// When you access
// import defaultListingFormValues from '...';
let categoryFromDropDown = 'dress';
let defaultValue = defaultListingFormValues[categoryFromDropDown] ?
defaultListingFormValues[categoryFromDropDown].itemWeight :
defaultListingFormValues.itemWeight;
console.log(defaultValue);
// category which is not present in defaultListingFormValues.
categoryFromDropDown = 'aaa';
defaultValue = defaultListingFormValues[categoryFromDropDown] ?
defaultListingFormValues[categoryFromDropDown].itemWeight :
defaultListingFormValues.itemWeight;
console.log(defaultValue);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句