对路由的理解
在 pc 端页面之间的切换, 我们大多使用 a 链接, location 等操作.
在 react.js 开发中, 我们采用组件化操作, 一个页面就是一个组件. 所以页面和页面之间的跳转就相当于是组件和组件之间的跳转.
我们知道 react.js 是一种单页面项目开发, 就是在一个主页面的基础上存放各种子页面. 这就好像一根网线连接路由器, 而路由器能分出很多根网线连接大量的电脑. 所以我们将单页面项目的页面跳转称为路由.
在第一篇放出的框架中, 我们介绍过专门用来管理路由的文件 --routes.js 文件.
1, 使用 Link 进行路由跳转
(1)routes.js 中的配置
- import React from 'react'
- import { Route, IndexRoute } from 'react-router'
- import MyScreen from './containers/MyScreen';
- import {
- App,
- Home,
- } from './containers'
- export default (
- <Route path="/" component={App}>
- <IndexRoute component={Home}/>
- <Route path="my">
- <IndexRoute component={MyScreen}/>
- </Route>
- </Route>
- );
注意: 这里需要使用 react-router 功能模块, 一般都是框架中自带的, 如果没有可使用 npm 进行下载使用 (第一篇分享的框架的 package.json 中已经囊括了常用的功能资源).
(2)Home.js 中的代码
- import React,{ Component } from 'react'
- import MyScreen from "./MyScreen";
- import { Link } from 'react-router'
- class Home extends Component {
- constructor(props) {
- super(props);
- this.state = {
- };
- }
- render() {
- return (
- <div style={{width:"100%",height:"300px",fontSize:"20px"}}>
- <Link to="/my">
- <div id="div1" style={{width:"100%",height:"100px",backgroundColor:"#ff0",lineHeight:"100px",textAlign:"center"}}> 点击跳转 </div>
- </Link>
- </div>
- )
- }
- }
- export default Home
(3)MyScreen.js 中的代码:
- import React,{ Component } from 'react'
- class MyScreen extends Component {
- constructor(props) {
- super(props);
- this.state = {
- };
- }
- render() {
- return (
- <div style={{width:"100%",height:document.documentElement.clientHeight,fontSize:"12px",backgroundColor:"#0ff",textAlign:"center",lineHeight:"100px"}} onClick={()=>this.click()}>
- 这是 MyScreen 界面
- </div>
- )
- }
- click=()=>{
- alert("点击到了!!!!");
- };
- }
- export default MyScreen
2, 使用 push 的方式进行路由跳转
这一种相对于 Link 方法更加常用.
Home.js 代码
- import React,{ Component } from 'react'
- import MyScreen from "./MyScreen";
- import { Link } from 'react-router'
- class Home extends Component {
- static contextTypes = {
- router: React.PropTypes.object
- };
- constructor(props) {
- super(props);
- this.state = {
- };
- }
- render() {
- return (
- <div style={{width:"100%",height:"300px",fontSize:"20px"}}>
- <div id="div1" style={{width:"100%",height:"100px",backgroundColor:"#ff0",lineHeight:"100px",textAlign:"center"}} onClick={()=>this.click()}> 点击跳转 </div>
- </div>
- )
- }
- click=()=>{
- this.context.router.push("/my");
- };
- }
- export default Home
下面这种方法, 首先要增加静态变量, 里面进行路由的一些配置. 然后直接通过. router.push 进行调用. 其他两个文件与上面的一样, 不加修改.
来源: https://www.cnblogs.com/xukun588/p/9458725.html