我有一组对象。
前:
data=[
{
name: 'Person1',
age: 30,
weight: 200
},
{
name: 'Person2',
age: 30,
weight: 200
},
{
name: 'Person3',
age: 30,
weight: 200
}
]
我在数组中进行映射,只返回Person和age。
当我点击该人时,如何获得完整的对象数据。
例如我正在渲染以下内容。
我想console.log所有我点击的特定对象属性。
我正在努力简化这一点,我希望它不会令人困惑。
return(
//This is a function that is mapping through the objects and printing out each objects Name and age only
this.loopData()
)
loopData = ()=>{
return data.map(obj,i) =>{
return(<h1 onClick={this.showme} key={i}>{obj.name}</h1>}
}
我有onlick as showme =()=&gt; console.log(this)
如果信息存在,我会在哪个标签下寻找?
答案 0 :(得分:0)
如果要按字符串值访问对象属性,可以执行以下操作:
var data = {
Person1: {
age: 22,
weight: 180
}
};
var _clickedid = "Person1";
var _clickedobj = data[_clickedid];
console.log(_clickedobj);
答案 1 :(得分:0)
答案 2 :(得分:0)
根据我的理解,你正在努力实现这样的目标,但我可能会弄错。
const data = [
{
name: 'Person1',
age:30,
weight:200
},
{
name: 'Person2',
age:20,
weight:180
},
{
name: 'Person3',
age:10,
weight:100
}
]
const generateHtml = data => {
const list = document.createElement('ul');
document.body.appendChild(list);
for (let i = 0; i < data.length; i++) {
let item = document.createElement('li');
item.textContent = data[i].name;
list.appendChild(item)
item.addEventListener('click', event => {
console.log(data[i]);
});
}
}
generateHtml(data);
答案 3 :(得分:0)
On calling the below functional component renders a button with person name. Onclicking the person will log it in console
const renderPerson = () => {
let data=[
{
name: 'Person1',
age: 30,
weight: 200
},
{
name: 'Person2',
age: 30,
weight: 200
},
{
name: 'Person3',
age: 30,
weight: 200
}
]
return(
<div>
{data.map(person => (
<button onClick={() => console.log(JSON.stringify(person))}>person.name</button>
))}
</div>
)
}
答案 4 :(得分:0)
你应该绑定地图循环中的人,以便能够点击处理函数中点击的人。
showPerson(person) {
// do stuff
console.log(JSON.stringify(person))
}
render() {
let data = [
{
name: 'Person1',
age: 30,
weight: 200
},
{
name: 'Person2',
age: 30,
weight: 200
},
{
name: 'Person3',
age: 30,
weight: 200
}
];
return(
<div>
{
data.map(person => (
<button
onClick={this.showPerson.bind(null, person)}>
person.name
</button>
))
}
</div>
)
}