react的路由总体来说还是挺简单的,没用过老版本的,现在用的是react-router-dom@4.3.1
安装:npm install react-router-dom
引入:import { BrowserRouter as Router, Route, Link } from "react-router-dom";
使用:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import pageA from './views/a'
import pageB from './views/b'
class App extends Component{
render(){
return (
<Router>
<div>
<ul>
<li><Link to="/home">首页</Link></li>
<li><Link to="/other">其他页</Link></li>
</ul>
<Route path="/home" component={pageA}/>
<Route path="/other" component={pageB}/>
</div>
</Router>
)
}
}
所有的操作都标签化了,大概意思就是一个router当作根标签,里面嵌套一些子组件,Link to的值是多少,Router匹配的组件就显示,子组件的显示不会影响组件外的页面,只是相当于把<Route />标签替换为一整个子组件而已
代码:
index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import pageA from './views/a'
import pageB from './views/b'
class App extends Component{
render(){
return (
<Router>
<div>
<ul>
<li><Link to="/home">首页</Link></li>
<li><Link to="/other">其他页</Link></li>
</ul>
<Route path="/home" component={pageA}/>
<Route path="/other" component={pageB}/>
</div>
</Router>
)
}
}
export default App;
./views/a.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import logo from '../logo.svg';
class Appa extends Component {
constructor(props){
super(props);
this.state = {
val1:'state val1',
};
}
render() {
return (
<div>
<button onClick={event=>{this.testClick2()}}>
我是pageA的一个按钮
</button>
<p>{this.state.val1}</p>
</div>
)
}
testClick2(){
console.log(this.props.history)
this.props.history.push('/other')
}
}
export default Appa;
./views/b.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import logo from '../logo.svg';
class Appb extends Component {
constructor(props){
super(props);
this.state = {
val1:'walala',
val2:'buibuibui',
};
this.val = 'value 1';
console.log('app constructor')
}
render() {
return (
<div>
<button onClick={event=>{this.testClick2()}}>
我是pageB的一个按钮
</button>
<p>{this.state.val1}</p>
</div>
)
}
testClick2(){
console.log(this.props.history)
this.props.history.replace('/home')
}
}
export default Appb;
子组件中可以通过this.props.histroy.push('/home')或者this.props.history.replace('/other')等history操作,来实现整体路由的跳转