Toggle(show/hide) components onClick in 单页 React component useState

Toggle(show/hide) components onClick in single page React component useState

在下面的单页案例中,您如何在组件之间切换?理想情况下,当您单击 menu-item 时,关联的组件将显示而其他组件将隐藏。

反应

import React, { useState } from 'react';
import About from "./components/About";
import Projects from "./components/Projects";
import Contact from "./components/Contact";

const App = () => {
    // Toggle state(s) here?

    // Toggle function(s) here?

    return (
        <div className="nav">
            <ul className="menu">
                <li className="menu-item">About</li>
                <li className="menu-item">Projects</li>
                <li className="menu-item">Contact</li>
            </ul>
        </div>
        <div className="container">
            <About />
            <Projects />
            <Contact />
        </div>
    )
};

export default App;

一种简单的方法是根据当前状态渲染一个组件,然后改变状态来渲染另一个组件:

import React, { useState } from 'react';
import About from "./components/About";
import Projects from "./components/Projects";
import Contact from "./components/Contact";

const App = () => {
    const [page, setPage] = useState("about")

    return (
        <div className="nav">
            <ul className="menu">
                <li className="menu-item" onClick={() => setPage("about")}>About</li>
                <li className="menu-item" onClick={() => setPage("projects")}>Projects</li>
                <li className="menu-item" onClick={() => setPage("contact")}>Contact</li>
            </ul>
        </div>
        <div className="container">
            {page === "about" && <About />}
            {page === "projects" && <Projects />}
            {page === "contact" && <Contact />}
        </div>
    )
};

export default App;

你可能想让它更干净一点,但你有想法。

您可以管理菜单项的数组,选定的组件将呈现! 这是 codepen 演示!

const About=()=>"About us page";
const Projects=()=>"Projects page";
const Contact=()=>"Contact Page";
const App = () => {
   const menuItems =[
    {component:<About />, title:"About"},
    {component:<Projects />, title:"Projects"},
    {component:<Contact />, title:"Contact"}
   ];

   const [component, setComponent] = React.useState(menuItems[0].component);

    return (
      <div>
        <div className="nav">
            <ul className="menu">
                {
                  menuItems.map((item,i)=>
                    <li key={i} onClick={()=>setComponent(item.component)} className="menu-item">
                      {item.title}
                    </li>
                  )
                }
            </ul>
        </div>
        <div className="container">
           {component}
        </div>
       </div>
    );
};

ReactDOM.render(<App/>, document.getElementById("root"));