简述 demo 使用 create-react-app 直接创建 路由是使用 react-router-dom
稍微改变一下 create-react-app 创建后的src目录, 这里目录和vue相似
index.js 中不做改变
App.js 中 使用 react-router-dom 检测地址 检索 ‘/’ , ‘/views’ 两个路由
import React from 'react';
import { HashRouter, Route, Redirect} from "react-router-dom";
import './assets/css/App.less';
import Views from './views/Views'
function App() {
return (
<div className="App">
<HashRouter>
<Route path='/' render={()=>(<Redirect to='/views' />)}></Route>
<Route path='/views' component={Views}></Route>
</HashRouter>
</div>
);
}
export default App;
Views.js 是业务的容器,这个页面实现tabbar的包裹与跳转 react-router-dom 函数式跳转直接使用 this.props.history.push({ }) 参数参考 https://reacttraining.com/react-router/web/api/history
import React, { Component, Fragment } from "react";
import { Route, Redirect } from 'react-router-dom'
class Views extends Component {
constructor ( props ) {
super(props)
this.state = {}
}
render () {
return (
<Fragment>
<div className="views">
<div className="views-container">
<Route path="/views" render={()=> <Redirect replace to='/views/home' />}></Route>
<Route path="/views/home" component={require('./page/Home').default}></Route>
<Route path="/views/category" component={require('./page/Category').default}></Route>
<Route path="/views/fn" component={require('./page/Fn').default}></Route>
<Route path="/views/cart" component={require('./page/Cart').default}></Route>
<Route path="/views/me" component={require('./page/Me').default}></Route>
</div>
<footer className="footerFixed">
<button id={'home'} onClick={this.tabbClick}>首页</button>
<button id={'category'} onClick={this.tabbClick}>分类</button>
<button id={'fn'} onClick={this.tabbClick}>fn</button>
<button id={'cart'} onClick={this.tabbClick}>购物车</button>
<button id={'me'} onClick={this.tabbClick}>我的</button>
</footer>
</div>
</Fragment>
)
}
tabbClick = ( e ) => {
e.preventDefault()
switch ( e.target.id ) {
case 'home' :
this.props.history.push({
pathname: '/views/home'
});
break;
case 'category' :
this.props.history.push({
pathname: '/views/category'
});
break;
case 'fn' :
this.props.history.push({
pathname: '/views/fn'
});
break;
case 'cart' :
this.props.history.push({
pathname: '/views/cart'
});
break;
case 'me' :
this.props.history.push({
pathname: '/views/me'
});
break;
default: {
this.props.history.push({
pathname: '/views/home'
})
}
}
}
}
export default Views
demo