反应路由器导航栏示例 [英] React router nav bar example
问题描述
我是 React JS 的初学者,想为我的仪表板开发基于 React 路由器的导航.样机如下:
我为尝试路由而创建的 app.js 代码如下:
从 'react' 导入 React从'react-dom'导入{渲染}从反应路由器"导入{路由器,路由,链接}从'./components/Login.js'导入登录;const App = React.createClass({使成为() {返回 (<div><h1>应用</h1><ul><li><Link to="/login">登录</Link></li><li><Link to="/inbox">收件箱</Link></li>{this.props.children}
)}})使成为((<li><路由器><Route path="/" component={App}><Route path="login" component={Login}/></路线></路由器>), document.getElementById('placeholder'))
如何创建模型中显示的导航?
是的,Daniel 是正确的,但为了扩展他的答案,您的主要应用组件需要在其中包含导航栏组件.这样,当您呈现主应用程序(/"路径下的任何页面)时,它也会显示导航栏.我猜你不希望你的登录页面显示导航栏,所以它不应该是一个嵌套组件,而应该是它本身.所以你的路线最终会看起来像这样:
<路由器><Route path="/" component={App}><Route path="page1" component={Page1}/><Route path="page2" component={Page2}/></路线><Route path="/login" component={Login}/></路由器>
其他组件看起来像这样:
var NavBar = React.createClass({使成为() {返回 (<div><ul><a onClick={() =>history.push('page1') }>Page 1</a><a onClick={() =>history.push('page2') }>第 2 页</a>
)}});var App = React.createClass({使成为() {返回 (<div><导航栏/><div>其他内容</div>{this.props.children}
)}});
I am a beginner in React JS and would like to develop a react router based navigation for my Dashboard. The mockup is as follows:
My app.js code which I created to try routing is as follows:
import React from 'react'
import { render } from 'react-dom'
import { Router, Route, Link } from 'react-router'
import Login from './components/Login.js';
const App = React.createClass({
render() {
return (
<div>
<h1>App</h1>
<ul>
<li><Link to="/login">Login</Link></li>
<li><Link to="/inbox">Inbox</Link></li>
</ul>
{this.props.children}
</div>
)
}
})
render((
<li>
<Router>
<Route path="/" component={App}>
<Route path="login" component={Login} />
</Route>
</Router>
</li>
), document.getElementById('placeholder'))
How do I create the navigation as shown in the mockup ?
Yes, Daniel is correct, but to expand upon his answer, your primary app component would need to have a navbar component within it. That way, when you render the primary app (any page under the '/' path), it would also display the navbar. I am guessing that you wouldn't want your login page to display the navbar, so that shouldn't be a nested component, and should instead be by itself. So your routes would end up looking something like this:
<Router>
<Route path="/" component={App}>
<Route path="page1" component={Page1} />
<Route path="page2" component={Page2} />
</Route>
<Route path="/login" component={Login} />
</Router>
And the other components would look something like this:
var NavBar = React.createClass({
render() {
return (
<div>
<ul>
<a onClick={() => history.push('page1') }>Page 1</a>
<a onClick={() => history.push('page2') }>Page 2</a>
</ul>
</div>
)
}
});
var App = React.createClass({
render() {
return (
<div>
<NavBar />
<div>Other Content</div>
{this.props.children}
</div>
)
}
});
这篇关于反应路由器导航栏示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!