React - 在多个组件上管理 'active' 标志的一种状态
React - one state for managing 'active' flag on multiple compontents
我有一个要共享相同状态的组件列表。
我希望在任何给定时间只有最后选择的组件处于活动状态,而其他组件处于 'inactive'。
谢谢。
编辑:
对于潜在死链接的 SO 未来验证:
侧边栏列表组件:
const [active, setActive] = useState(false);
const handleActive = (i) => {
console.log(i);
i.currentTarget.className = active ? "a" : "b";
console.log(i.currentTarget.className);
};
const list = props.items.map((item) => {
return (
<ListItem key={item.id} handleActive={(item) => handleActive(item)}>
{item.text}{" "}
</ListItem>
);
});
return (
<div className="sidebar__list">
<h2>{props.title}</h2>
<ul>{list}</ul>
</div>
);
}
ListItem 组件
function List_item(props) {
return (
<li onClick={props.handleActive}>
<a>
<h2>{props.children}</h2>
</a>
</li>
);
}
export default List_item;
以及 App 组件:
export default function App() {
return (
<div className="App">
<SidebarList
title="About"
items={[
{ id: 1, text: "Item 1 arr" },
{ id: 2, text: "Item 2 arr" }
]}
/>
<SidebarList
title="Templates"
items={[
{ id: 1, text: "Item 1 arr" },
{ id: 2, text: "Item 2 arr" }
]}
/>
</div>
);
}
TLDR; react router v4 NavLink 根据当前路由页面对一个活动类名进行单一维护。
NavLink 属性 'activeClassName' 将指定的类名解析为当前路由页面,同时在非路由页面上删除。因此,该问题中的所有状态管理都是多余的。
我有一个要共享相同状态的组件列表。
我希望在任何给定时间只有最后选择的组件处于活动状态,而其他组件处于 'inactive'。
谢谢。
编辑: 对于潜在死链接的 SO 未来验证:
侧边栏列表组件:
const [active, setActive] = useState(false);
const handleActive = (i) => {
console.log(i);
i.currentTarget.className = active ? "a" : "b";
console.log(i.currentTarget.className);
};
const list = props.items.map((item) => {
return (
<ListItem key={item.id} handleActive={(item) => handleActive(item)}>
{item.text}{" "}
</ListItem>
);
});
return (
<div className="sidebar__list">
<h2>{props.title}</h2>
<ul>{list}</ul>
</div>
);
}
ListItem 组件
function List_item(props) {
return (
<li onClick={props.handleActive}>
<a>
<h2>{props.children}</h2>
</a>
</li>
);
}
export default List_item;
以及 App 组件:
export default function App() {
return (
<div className="App">
<SidebarList
title="About"
items={[
{ id: 1, text: "Item 1 arr" },
{ id: 2, text: "Item 2 arr" }
]}
/>
<SidebarList
title="Templates"
items={[
{ id: 1, text: "Item 1 arr" },
{ id: 2, text: "Item 2 arr" }
]}
/>
</div>
);
}
TLDR; react router v4 NavLink 根据当前路由页面对一个活动类名进行单一维护。
NavLink 属性 'activeClassName' 将指定的类名解析为当前路由页面,同时在非路由页面上删除。因此,该问题中的所有状态管理都是多余的。