在单页中切换(显示/隐藏)组件onClick React组件useState

时间:2020-01-09 05:48:24

标签: javascript reactjs react-functional-component

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

2 个答案:

答案 0 :(得分:2)

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

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;

您可能想使其更清洁一点,但是您有主意。

答案 1 :(得分:1)

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

0