react项目的react-router-dom路由的使用

时间:2024-12-18 19:07:38

现在测试一下react-router-dom路由的使用,首先在App.js这个文件搭配路由

import React, { Component } from 'react';
import {Link, Route, Switch} from "react-router-dom";
import './App.css';
import first from "../first/first";
import second from "../second/second";
import qqq from "../qqq/qqq"; class App extends Component {
render() {
return (
<div className="App">
<ul>
<li><Link to='/'>首页</Link></li>
<li><Link to='/first'>first</Link></li>
<li><Link to='/second'>second</Link></li>
</ul>
<Switch>
<Route exact path="/" component={qqq} />
<Route exact path="/first" component={first} />
<Route exact path="/second" component={second} />
</Switch>
</div>
);
}
} export default App;

然后创建文件(测试),这是是三个文件

react项目的react-router-dom路由的使用

这样的三个文件

import React, { Component } from 'react';

class first extends Component {
render() {
return (
<div style={{ padding:"200px" }}>
1111111111111111111111111111111111111111111111111111111111111111111111111
</div>
);
}
} export default first;

这样还会出现一个问题,运行错误,是关于路由的,需要套上<BrowserRouter></BrowserRouter>,可以在App.js的路由外面套上,这里是在根文件index.js套上<App />

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from "./App/App";
import * as serviceWorker from './serviceWorker';
import {BrowserRouter} from "react-router-dom"; ReactDOM.render(<BrowserRouter><App /></BrowserRouter>, document.getElementById('root')); // If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.unregister();

这样就完成了react-router-dom路由

react项目的react-router-dom路由的使用