💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
## 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里的内容 } ~~~