当单击链接时,是否可以在同一位置呈现不同的组件?
我的页面中有一个SideNav
和一个TopNav
组件在APP
组件中。我想要做的是在页面中间插入一个Thrind组件,当单击不同的链接和按钮时,该组件将显示不同的结果。
我的应用程序组件就像
import {SideNav} from "./SideNav";
import {TopNav} from "./TopNav";
class App extends React.Component {
render() {
return (
<div className={'container'}>
<SideNav />
<TopNav />
<div className={'content'}>
Content will be rendered here on clicking the link but how?
</div>
</div>
);
}
}
我想在容器类中显示不同的组件。怎样才能做到这一点呢?
import {BrowserRouter as Router, Route, Link, Switch} from "react-router-dom";
class SideNav extends React.Component{
render() {
return (
<div className={"sidenav"}>
<Router>
<Link href="#">About</Link>
<Link href="#">Services</Link>
<Link href="#">Clients</Link>
<Link href="#">Contact</Link>
</Router>
</div>
);
}
}
我希望通过点击链接在同一个地方呈现不同的组件。例如,如果我单击Home
,我希望显示主页,而不是显示页面中间现有内容的主页。程序是什么。
“我的Home
Hello World
组件”( My Component MyComponentMyComponentMyComponentMyComponent)现在只显示Hello World
(现在是)。
发布于 2019-09-05 06:30:39
您需要使用路由器而不是导航组件包装您的内容。如下所示:
function App() {
return (
<div className="App">
<Router>
<div className={"container"}>
<SideNav />
<Switch>
<Route exact path="/">
Some home content
</Route>
<Route path="/services">Some Services content</Route>
<Route path="/clients">Some Clients content</Route>
<Route path="/about">
<About />
</Route>
<Route path="/contact">Some Contact content</Route>
</Switch>
<div className={"content"}>
Content will be rendered here on clicking the link but how?
</div>
</div>
</Router>
</div>
);
}
然后在导航组件中,只需使用以下链接:
class SideNav extends React.Component {
render() {
return (
<div className={"sidenav"}>
<Link to="/about">About</Link>
<Link to="/services">Services</Link>
<Link to="/clients">Clients</Link>
<Link to="/contact">Contact</Link>
</div>
);
}
}
我给您做了一个工作沙箱示例这里。
https://stackoverflow.com/questions/57807232
复制