Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

reactjs - React - one state for managing 'active' flag on multiple compontents

I have a list of compontents I want to share the same state.

I want, at any given time, only the last selected component to have the active state whilst the others to be 'inactive'.

codesandbox link

Thanks.

EDIT: for SO future proofing of potential dead links:

SidebarList Compontent:

  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 compontent

function List_item(props) {
  return (
    <li onClick={props.handleActive}>
      <a>
        <h2>{props.children}</h2>
      </a>
    </li>
  );
}

export default List_item;

And the App component:

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>
  );
}
question from:https://stackoverflow.com/questions/66066346/react-one-state-for-managing-active-flag-on-multiple-compontents

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

TLDR; react router v4 NavLink perform singular maintenance of one active className, dependant on the current routed page.

NavLink property 'activeClassName' will parse a specfied className to the current routed page, whilst removing on non-routed pages. All state management in this question is therefore redundant.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...