为了方便学习React路由,这里记录示例创建过程。
1、创建react app
#创建
npx create-react-app sample
#进入目录
cd sample
2、修改public/index.html
<html>
<head>
<title>React 路由</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
3、修改 src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
4、修改src/App.js
import React from 'react';
import { BrowserRouter as Router,Route,Link} from 'react-router-dom';
function Home () {
return (
<div>
<span>主页</span>
<Link to="/page">其他页面</Link>
</div>
);
}
function Page () {
return (
<div>
<span>其他页面</span>
<Link to="/">主页</Link>
</div>
);
}
function App() {
return (
<Router>
<div>
<Route path="/" exact={true} component={Home} />
<Route path="/page" exact={true} component={Page} />
</div>
</Router>
);
}
export default App;
5、安装依赖 react-router-dom
yarn add react-router-dom
6、执行看效果
yarn start