【问题标题】:React - one state for managing 'active' flag on multiple compontentsReact - 用于管理多个组件上的“活动”标志的一种状态
【发布时间】:2021-05-09 23:26:12
【问题描述】:

我有一个想要共享相同状态的组件列表。

我希望在任何给定时间,只有最后一个选定的组件处于活动状态,而其他组件处于“非活动”状态。

codesandbox link

谢谢。

编辑: 用于潜在死链接的未来证明:

SidebarList 组件:

  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>
  );
}

【问题讨论】:

    标签: reactjs react-props use-state


    【解决方案1】:

    TLDR; react router v4 NavLink 对一个活动的 className 执行单一维护,具体取决于当前路由页面。

    NavLink 属性“activeClassName”会将指定的类名解析为当前路由页面,同时在非路由页面上删除。因此,这个问题中的所有状态管理都是多余的。

    【讨论】:

      猜你喜欢
      • 2018-08-05
      • 1970-01-01
      • 2018-03-13
      • 1970-01-01
      • 2020-09-25
      • 2021-03-28
      • 2018-05-24
      • 1970-01-01
      • 2022-10-24
      相关资源
      最近更新 更多