我是Reactjs的新手。我从外部js文件路由时遇到问题。
这是我在top-header.js中的导航文件代码
import React from 'react';
import {BrowserRouter as Router, Link} from 'react-router-dom';
function Header(props) {
return <div>
<ul>
<Router>
<li><Link to="/">Home</Link></li>
<li><Link to="/about-us">About</Link></li>
<li><Link to="/contact-us">Contact</Link></li>
</Router>
</ul>
</div>
}
export default Header;
这是我的主要app.js文件
import 'bootstrap/dist/css/bootstrap.min.css';
import './App.css';
import {BrowserRouter as Router, Route, Switch,Link} from 'react-router-dom';
import Header from './utils/top-header.js';
/*pages*/
import Home from './utils/pages/home.js';
import Contact from './utils/pages/contact.js';
import About from './utils/pages/about.js';
function App() {
return (
<div>
<Header />
<Router>
//this Link code works when directly added to app.js file//
<li><Link to="/">Home</Link></li>
<li><Link to="/about-us">About</Link></li>
<li><Link to="/contact-us">Contact</Link></li>
<Switch>
<Route exact path="/" component={Home}></Route>
<Route path="/about-us" component={About}></Route>
<Route path="/contact-us" component={Contact}></Route>
</Switch>
</Router>
</div>
);
}
export default App;
答案 0 :(得分:1)
问题在于您的Router(BrowserRouter)组件仅包装了链接,而将所有Links,Routes,Switchs包装在BrowserRouter组件中。
function Header(props) {
return <div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about-us">About</Link></li>
<li><Link to="/contact-us">Contact</Link></li>
</ul>
</div>
}
function App() {
return (
<Router>
<div>
<Header />
//this Link code works when directly added to app.js file//
<li><Link to="/">Home</Link></li>
<li><Link to="/about-us">About</Link></li>
<li><Link to="/contact-us">Contact</Link></li>
<Switch>
<Route exact path="/" component={Home}></Route>
<Route path="/about-us" component={About}></Route>
<Route path="/contact-us" component={Contact}></Route>
</Switch>
</div>
</Router>
);
}
通常我将其放入index.js中,包装好App组件