我在 React 中有一个对象,我映射并想让它交互:我想要它,所以当用户单击元素旁边的“X”按钮时,它会在 console.log 中记录该单击元素的键。
这是对象:
var obj = {
person1: {
name: 'iggy',
superPower: 'awesomeness',
favDonut: 'chocolate'
},
person2: {
name: 'iggy2',
superPower: 'stupendousness',
favDonut: 'glazed'
},
person3: {
name: 'iggy3',
superPower: 'amazingness',
favDonut: 'chocolate sprinkles'
}
};
迭代看起来像这样:
X chocolate
X glazed
X chocolate sprinkles
如果我单击 x on glazed
,我希望它到 console.logperson2
因为那是glazed
. 如果我点击 x chocolate sprinkles
,我希望它到 console.log person3
。
这是小提琴:https : //jsfiddle.net/iggyfiddle/b9rreoje/2/
我想弄清楚的方法是getPersonName
函数。允许用户单击 x 和 console.log 相关对象键的最佳方法是什么?
而不是做Object.values
你想做的Object.keys
,这样你就可以访问相应的密钥。
getPersonName: function(person){
console.log(person);
}
const donutValues = Object.keys(obj).map((key, index) => <li key={index}><a href="#" onClick={() => this.getPersonName(key)}>X</a> {obj[key].favDonut} </li>);
更新小提琴:https : //jsfiddle.net/b9rreoje/3/
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句