【发布时间】:2022-06-22 21:33:29
【问题描述】:
我正在尝试实现一个逻辑,其中基于单击的项目,arrow down 图标更改为arrow-up,如果用户第二次单击同一行应该再次更改。
我试图触发它基于在点击项目的索引上,但不能正常工作。
还尝试根据此处的布尔状态更改更改图标
const handleClick = () => {
setOpen(!open);
};
但是这种方法会改变状态中所有图标的状态。
这是代码和sandbox link。
import React, { useState } from "react";
import { ListGroup } from "react-bootstrap";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faAngleUp, faAngleDown } from "@fortawesome/free-solid-svg-icons";
export const defaultListData = [
{
name: "Dapibus ac facilisis in"
},
{
name: "Morbi leo risus"
},
{
name: "Porta ac consectetur ac"
},
{
name: "Porta ac doesfvsaard asdas"
}
];
function UserSettings() {
const [open, setOpen] = useState(false);
const [selectedIndex, setSelectedIndex] = useState(0);
const handleClick = () => {
setOpen(!open);
};
function handleTests(index) {
setSelectedIndex(index);
}
return (
<div>
{defaultListData.map((category, i) => (
<ListGroup key={category.name} variant="flush">
<ListGroup.Item
onClick={(e) => handleTests(i)}
style={{ display: "flex", gap: "50px" }}
>
{category.name}
<FontAwesomeIcon
style={{ color: "green", cursor: "pointer" }}
icon={selectedIndex === i ? faAngleDown : faAngleUp}
/>
</ListGroup.Item>
</ListGroup>
))}
</div>
);
}
export default UserSettings;
任何帮助将不胜感激
【问题讨论】:
-
您只需要将每个列表数据项映射到其自己的组件,以便每个组件都有自己的
open状态。然后在单击图标时切换该状态。
标签: javascript reactjs