## 1.配置路由
1.1 打開命令行,加載`react-router-dom`包
~~~
$ npm install --save react-router-dom
~~~
2.2 新建router.js配置路由
~~~
import React from 'react'
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import App from './App'
import Page2 from './Component/Page1'
import Page3 from './Component/Page2'
const AppRouter = () => (
<Router>
<div>
<Route path="/" exact component={App} />
<Route path="/Page2" component={Page2} />
<Route path="/Page3" component={Page3} />
</div>
</Router>
);
export default AppRouter;
~~~
2.3 主目錄`index.js`render的對象更改為AppRouter
~~~
import React from 'react';
import ReactDOM from 'react-dom';
import AppRouter from './router';
ReactDOM.render(<AppRouter />, document.getElementById('root'));
~~~
## 2.頁面跳轉
### 1.方式
##### 1.1Link組件
~~~
import React from 'react'
import { Link } from 'react-router-dom'
?
export default class Demo extends React.Component {
? ?
? ?render() {
? ? ? ?return(
? ? ? <div>
? ? ? ? ? <Link to='/pathName'>跳轉頁面</Link>
? ? ? ? ? ?</div>
? ? ? )
? }
}
~~~
#### 1.2使用 withRouter (react-router v4)
~~~
import React from 'react'
import { withRouter } from 'react-router-dom';
?
class Demo extends React.Component {
? ?onClick = () => {
console.error('props',this.props)
this.props.history.push('/pathName')
}
? ?render() {
? ? ? ?return(
? ? ? <div>
? ? ? ? ? <button onClick={this.onClick}>跳轉頁面</button>
? ? ? ? ? ?</div>
? ? ? )
? }
}
export default withRouter(Demo)
~~~
### 2.頁面跳轉傳參
##### 2.1 state
~~~
import React from 'react'
import { Link } from 'react-router-dom'
?
export default class Demo extends React.Component {
? ?
? ?constructor(props) {
? ? ? ?super(props);
? ? ? ?this.state={
? ? ? ? ? ?name: 'xiaoPi',
? ? ? ? ? ?age: 22
? ? ? }
? }
? ?
? ?render() {
? ? ? ?const { name, age } = this.state
? ? ? ?return(
? ? ? <div>
? ? ? ? ? <Link to={{ pathname: '/pathName', state: this.state }}>跳轉頁面</Link>
? ? ? ? ? <Link to={{ pathname: '/pathName2', state: {name: name, age: age} }}>跳轉頁面2</Link>
? ? ? ? ? ?</div>
? ? ? )
? }
}
~~~
在頁面接收參數
~~~
componentWillMount(){
? console.error('參數值',this.props.location) //可以獲取所有傳遞過來的內容
? console.log('state',this.props.location.state)//頁面傳參時放在state里的內容
}
~~~
##### 2.2 query,與state傳參基本一致
~~~
render() {
? const { name, age } = this.state
? return(
? ? ? <div>
? ? ? ? ? <Link to={{ pathname: '/pathName', query: this.state }}>跳轉頁面</Link>
? ? ? ? ? <Link to={{ pathname: '/pathName2', query: {name: name, age: age} }}>跳轉頁面2</Link>
? ? ? </div>
? )
}
~~~
在頁面接收參數
~~~
componentWillMount(){
? ?console.error('參數值',this.props.location) //可以獲取所有傳遞過來的內容
? ?console.log('query',this.props.location.state)//頁面傳參時放在state里的內容
}
~~~