这是我的代码:
let user = [
{id: 1, name: "Chris", active: "true"},
{id: 2, name: "James", active: "true"},
{id: 3, name: "Jeremy", active: "true"},
];
handleClick = () => {
for(let i in user) {
if (Object.hasOwnProperty.call(user, i)) {
user[i].active = false;
}
}
};
嗨
我一直在研究许多主题,但找不到任何答案。
您可以在一次点击(handleClick)上看到,我想将active的状态从“ true”修改为“ false”,反之亦然。但是我希望这种情况仅发生在我单击的用户上,而不是全部发生。每个用户都有自己的按钮。
我开始认为也许我应该以某种方式使用id。
在函数中传递用户的ID,然后添加if语句
(id) =>{ user.forEach( obj =>{
If(obj.id === id)
obj.active = !obj.active;
})}
这里是解决方法:
enter code here
let user = [
{id: 1, name: "Chris", active: "true"},
{id: 2, name: "James", active: "true"},
{id: 3, name: "Jeremy", active: "true"},
];
handleClick = id => {
user.forEach( obj => {
if(obj.id === id)
obj.active = !obj.active;
});
};
如果尝试使用ES6
,也要使用boolean
来处理此功能,您应该在不使用true
或false
的情况下写quotation
或double-quotation
let user = [{
id: 1,
name: "Chris",
active: true
},
{
id: 2,
name: "James",
active: true
},
{
id: 3,
name: "Jeremy",
active: true
},
];
function handleClick(id) { // handleClick = (id) => {
const result = user.map(obj =>
obj.id === id ? { ...obj,
active: !obj.active
} : obj
)
console.log(result)
}
<div onclick="handleClick(1)">Click</div>
<!-- React version -> <div onClick="this.handleClick(id)">Click</div> -->