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 包提供的組件或高階組件來配置路由規則和獲取路由信息。具體使用哪種方法,可以根據項目需求和個人偏好進行選擇。