我是 React 的新手,我对 React Router Dom 有问题。 我正在开发一个单页应用程序,供我的简历练习和 我有一个汉堡菜单,我使用"链接"来匹配好的URL。我希望此链接加载关联的组件,但我必须刷新页面以加载所需的组件。
我读了很多不同的方法来解决这个问题,并尝试了其中的大多数,但没有人帮助我解决我的problem。
此处应用.js:
import Formations from "./formations/formations";
import Experiences from "./experiences/experiences";
import BM from "./BM/BM";
import {
BrowserRouter as Router,
Switch,
Route,
Link,
withRouter,
} from "react-router-dom";
class App extends React.Component {
render() {
return (
<div className="App">
<Header />
<p className="App-intro">{this.state.apiResponse}</p>
<Router>
<div>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/formations" component={Formations} />
<Route path="/experiences" component={Experiences} />
</Switch>
</div>
</Router>
<div className="bottomPage">
<p>down page</p>
</div>
</div>
);
}
}
我的汉堡菜单组件位于头文件头中.js :
import React from "react";
import "./Header.css";
import BM from "../BM/BM";
class Header extends React.Component {
render() {
return (
<div className="headerStyle">
<header>
<img src=""></img>
<p>GF</p>
<div id="outer-container">
<BM />
</div>
</header>
</div>
);
}
}
export default Header;
最后这是我的汉堡菜单:
import React from "react";
import { pushRotate as Menu } from "react-burger-menu";
import { BrowserRouter as Router, Link, Route, Switch} from 'react-router-dom'
import "./BM-styles.css";
class BM extends React.Component {
render() {
return (
<Menu>
<Router>
<li><Link to="/" className="menu-item">
Home
</Link></li>
<p className="bar">/</p>
<li><Link to="/experiences" className="menu-item" >
Expériences
</Link></li>
<p className="bar">/</p>
<li><Link to="/formations" className="menu-item" >
Formations
</Link></li>
<p className="bar">/</p>
<li><Link to="/loisirs" className="menu-item">
Loisirs
</Link></li>
</Router>
</Menu>
);
}
}
export default BM;
我已经尝试使用"withRouter((",但没有任何反应...... 我认为这是因为链接必须在交换机和路由器旁边,但我该怎么办? 如果有人能帮我:) 谢谢
你应该把你的<Header />
移到Router
,
class App extends React.Component {
render() {
return (
<div className="App">
<Router>
<Header />
<p className="App-intro">API response</p>
<div>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/formations" component={Formations} />
<Route path="/experiences" component={Experiences} />
</Switch>
</div>
</Router>
<div className="bottomPage">
<p>down page</p>
</div>
</div>
);
}
}
从组件中删除<Router>
BM
,
class BM extends React.Component {
render() {
return (
<Menu>
<li><Link to="/" className="menu-item">
Home
</Link></li>
<p className="bar">/</p>
<li><Link to="/experiences" className="menu-item" >
Expériences
</Link></li>
<p className="bar">/</p>
<li><Link to="/formations" className="menu-item" >
Formations
</Link></li>
<p className="bar">/</p>
<li><Link to="/loisirs" className="menu-item">
Loisirs
</Link></li>
</Menu>
);
}
}
演示