React 路由配置有多种方法,常用的有以下几种:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
function App() {
return (
<Router>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</Router>
);
}
import { Route } from 'react-router-dom';
function App() {
return (
<>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</>
);
}
import { withRouter } from 'react-router-dom';
function MyComponent(props) {
// 可以通过 props 获取路由信息,如 props.history, props.location, props.match
return <div>Hello React Router!</div>;
}
export default withRouter(MyComponent);
以上方法都是使用了 react-router-dom 包提供的组件或高阶组件来配置路由规则和获取路由信息。具体使用哪种方法,可以根据项目需求和个人偏好进行选择。