2

在下面的单页案例中,如何在组件之间切换?理想情况下,当您单击时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;
4

2 回答 2

7

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

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;

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

于 2020-01-09T05:55:38.460 回答
3

您可以管理菜单项的数组,并且选定的组件将呈现!这是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"));
于 2020-01-09T06:05:44.863 回答