[英]Toggle(show/hide) components onClick in single page React component useState
How do you toggle between components in the single page case below?在下面的单页案例中如何在组件之间切换? Ideally, when you click the
menu-item
the associated component will show and the others will hide.理想情况下,当您单击
menu-item
,关联的组件将显示,而其他组件将隐藏。
React反应
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;
A simple way is to render a component based on the current state and change the state to render another component:一种简单的方法是根据当前状态渲染一个组件并更改状态以渲染另一个组件:
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;
You probably want to make it a little cleaner but you have the idea.你可能想让它更干净一点,但你有这个想法。
You can manage an array for menu items and selected component will render!您可以管理菜单项的数组,所选组件将呈现! Here is the codepen demo!
这是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"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.