我有一个Nav.js文件和一个App.js文件
Nav.js -
import { Link, Router } from 'react-router-dom'
render() {
return (
<Router>
<ul className="nav-list">
<li><Link to="/">Home<Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</Router>
)
}
App.js -
import Nav from './nav.js'
import { BrowserRouter as Router, Route, Switch } from "react-router-dom"
render() {
return (
<Nav />
<Router>
<Switch>
<Route exact path="/" />
<Route exact path="/about" />
<Route exact path="/contact" />
</Switch>
</Router>
)
}
由于某些原因,这不起作用,但我觉得它应该基于react-router-dom docs。 React Router似乎应该很简单,但我在学习曲线上遇到了困难。我无法按照我希望的方式开展工作。有谁知道如何设置这种方式或有一个很好的参考,为我澄清一些事情?
答案 0 :(得分:0)
在create-react-app创建的应用程序中(我正在使用reactstrap,但您可以将其删除而不使用它):
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import Nav from './components/Navigation'; // top (fixed) navigation
import Footer from './components/Footer'; // bottom (fixed) footer
import Home from './components/Home';
import One from './components/One';
import Two from './components/Two';
...
ReactDOM.render(
<Provider store={store}>
<div>
<BrowserRouter>
<div>
<Route path="/" component={Navigation} />
<Switch>
<Route exact path="/" component={Home} />
<Route path="/one" component={One} />
<Route path="/two" component={Two} />
</Switch>
<Footer />
</BrowserRouter>
</div>
</Provider>
, document.querySelector('#root'));
import React from 'react';
import { Collapse, Navbar, NavbarToggler, NavbarBrand, Nav, NavItem, NavLink } from 'reactstrap';
import { Link } from 'react-router-dom';
class Navigation extends React.Component {
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.state = {
isOpen: false
};
}
toggle() {
this.setState({
isOpen: !this.state.isOpen
});
}
render() {
return (
<div>
<Navbar color="faded" light expand="md">
<NavbarBrand tag={Link} to="/">
<img src="/assets/images/book_lover.png" alt="book-lover!" />
</NavbarBrand>
<Nav className="ml-auto" navbar>
<NavItem>
<NavLink tag={Link} to="#">
</NavLink>
</NavItem>
</Nav>
<NavbarToggler onClick={this.toggle} />
<Collapse isOpen={this.state.isOpen} navbar>
<Nav className="ml-auto" navbar>
{this.props.loginEmail && <NavItem>
<NavLink tag={Link} to="/cats">Book-Categories</NavLink>
</NavItem>}
<NavItem>
<NavLink tag={Link} to="/howto">How-To-Use-This-Site</NavLink>
</NavItem>
<NavItem>
<NavLink tag={Link} to="/about">About</NavLink>
</NavItem>
</Nav>
</Collapse>
</Navbar>
<hr />
</div>
);
}
答案 1 :(得分:0)
您可以在两个文件中解决此问题 但在同一个BrowserRouter标签中,你在给定的样本中错过了这个。它应该是,
import Nav from './nav.js'
import { BrowserRouter, Route, Switch } from "react-router-dom"
render() {
return (
<BrowserRouter>
<Nav />
<Switch>
<Route exact path="/" />
<Route exact path="/about" />
<Route exact path="/contact" />
</Switch>
</BrowserRouter>
)
}
希望这会对你有所帮助。