大家好,我是梅巴哥er
,本篇介绍react-router的初级应用,实现跳转页面和4.0版history应用.
老规矩,先看效果图:
代码展示:
在/src
文件夹里,新建文件夹/router
(我们把所有关于路由的文件都放在这个文件夹里),然后在该文件夹里新建3个文件,
它们分别是:
- App.js
- Index.js
- List.js
如图:
三个文件各自的代码:
App.js
//这里需要注意的是新版的history怎么引用和应用的
import React, {
Component } from 'react'
import ReactDOM from 'react-dom'
import {
Router, Route } from 'react-router'
import {
createBrowserHistory } from "history"
import Index from './Index'
import List from './List'
const history = createBrowserHistory()
class App extends Component {
render() {
return (
<div>
<ul>
<li>
<a href="/index">首页</a>
</li>
<li>
<a href="/list">列表页</a>
</li>
</ul>
</div>
)
}
}
let routes = <Router history={
history }>
<Route path='/' exact component={
App } />
<Route path='/index' component={
Index } />
<Route path='/list' component={
List } />
</Router>
ReactDOM.render(
routes,
document.getElementById('root')
)
export default App
Index.js:
import React, {
Component } from 'react'
class Index extends Component {
render() {
return (
<h2>首页内容</h2>
)
}
}
export default Index
List.js:
import React, {
Component } from 'react'
class List extends Component {
render() {
return (
<h2>列表页内容</h2>
)
}
}
export default List
注意: 写到这里,并没有结束。因为react的文件入口是/src/index.js
文件,所以还要调整一下index.js
文件的代码:
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './router/App';
好了,没了。注意,这里的ReactDOM
是在/router/App.js
这个文件里进行渲染的。而不是在index.js
里进行渲染的。
然而,写到这里,并没有结束,因为还有更好的实现方法。暂时先写到这里,后续补充新的实现方法。
------------end