持续导航反应
React的新手和尝试使用React-Router在我的应用程序中创建持久导航的麻烦。
使用create-react-app
和"react-router": "^3.0.2"
我正在尝试在页面顶部添加一些导航,并附带一些链接。 我一直收到的错误是Uncaught Error: <Link>s rendered outside of a router context cannot navigate.
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { browserHistory } from 'react-router';
import { Router, Route } from 'react-router';
import Routes from './routes';
import App from './components/App';
import './index.css';
import Navigation from './components/Navigation';
ReactDOM.render(
<div>
<Navigation />
<Routes history={browserHistory} />
</div>,
document.getElementById('root')
);
导航/ index.js
import React, { Component } from 'react';
import { Link } from 'react-router';
class Navigation extends Component {
render() {
return (
<div>
<ul>
<li><Link to="about">About</Link></li>
<li><Link to="not-found">Not Found</Link></li>
</ul>
</div>
);
}
}
export default Navigation;
routes.js
import React from 'react';
import { Router, Route, IndexRoute, Link, browserHistory } from 'react-router';
import App from './components/App';
import About from './components/About';
import NotFound from './components/NotFound';
import Navigation from './components/Navigation';
const Routes = (props) => (
<div>
<Router {...props}>
<Route path="/" component={App} />
<Route path="/about" component={About}/>
<Route path="*" component={NotFound} />
</Router>
</div>
);
export default Routes;
我可以通过url导航(即localhost:8080 / about)并呈现正确的页面。 但无法弄清楚如何使导航工作并呈现正确的链接。
您应该将Navigation
组件呈现为您的App
组件的一部分,而不是在您的index.js
App
应该看起来像
class App extends Component {
render() {
return (
<div>
<Navigation />
{this.props.children}
</div>
);
}
}
你的路线也需要改变一点。
<Router {...props}>
<Route path="/" component={App}>
{/* If you have a home page in your App component already, move it to a Home component */}
<IndexRoute component={Home} />
<Route path="/about" component={About}/>
<Route path="*" component={NotFound} />
</Route>
</Router>
React路由器会将子路由中的组件作为子路由传递给父路由。
例如,在他们的文档中查看介绍示例。
链接地址: http://www.djcxy.com/p/52133.html