3 回答
TA贡献1827条经验 获得超8个赞
尝试将 User.js 更改为以下内容
className 根据选择的用户动态设置
Referlink -代码沙箱
import React from "react";
import { USERS_DATA } from "./data.js";
export default function User({ getUser, userSelected }) {
const selectUserClick = ({ target }) => {
let selectedUserIndex = USERS_DATA[target.value];
let username = `${selectedUserIndex.first_name} ${selectedUserIndex.last_name}
- ${selectedUserIndex.occupation}`;
let usermemo = `"${selectedUserIndex.catch_phrase}"`;
// userSelected = target.classList.toggle("selected");
getUser(username, usermemo, selectedUserIndex);
};
return (
<div className="users-container">
<ul>
{USERS_DATA.map((user, index) => (
<li
key={index}
value={user.id - 1}
onClick={selectUserClick}
className={`users ${
userSelected && user.id === userSelected.id ? "selected" : ""
}`}
>
{user.user_name}
</li>
))}
</ul>
</div>
);
}
TA贡献1786条经验 获得超11个赞
在您的情况下,只要您不需要一次选择多个选项,这样的事情就可以工作。运行一个函数,获取所有附加有“selected”类名的用户,并在进行新选择之前将其关闭。
const selectUserClick = ({ target }) => {
resetHighlights();
let selectedUserIndex = USERS_DATA[target.value];
let username = `${selectedUserIndex.first_name} ${selectedUserIndex.last_name} - ${selectedUserIndex.occupation}`;
let usermemo = `"${selectedUserIndex.catch_phrase}"`;
userSelected = target.classList.toggle("selected");
getUser(username, usermemo, userSelected);
};
function resetHighlights() {
var arr = document.getElementsByClassName("users");
for (var x = 0; x < arr.length; x++) {
if (arr[x].classList.contains("selected")) {
arr[x].classList.toggle("selected");
}
}
}
TA贡献1757条经验 获得超8个赞
另一种方法是:
我在代码中添加了简短的注释
export default function User({
getUser,
userSelected
}) {
const selectUserClick = ({
target
}) => {
let selectedUserIndex = USERS_DATA[target.value];
let username = `${selectedUserIndex.first_name} ${selectedUserIndex.last_name}
- ${selectedUserIndex.occupation}`;
let usermemo = `"${selectedUserIndex.catch_phrase}"`;
// get all li elements of selected users
let usersEl = document.getElementsByClassName("users selected");
let usersList = [...usersEl];
// assigns exisiting class to toggled class beforre selection
usersList.forEach((element) => {
element.className = "users";
});
// style only current selected el
userSelected = target.classList.toggle("selected");
getUser(username, usermemo, userSelected);
};
添加回答
举报