react路由传值、react路由监听、react过渡动画、react虚拟DOM树、react路由切换动画

1.编导式导航跳转路由传值

1.1url路由拼接传值

this.props.history.push(‘/user?title=’+params[0])

url路由拼接传值目标组件使用this. props.location.search取值,取值如下:

 路由url拼接传值:{decodeURI(props.location.search)}

 1.2 动态路由传值

this.props.history.push(‘/user/’+params[0])

 1.3 自定义对象传值

this.props.history.push({

​ pathname:‘/user’,

​ data:{

​ title

​ }

})

 

 2.路由监听

1,在页面卸载时,取消监听 2,在全局根组件app中监听路由

  var cancel =  props.history.listen((route,type)=>{
        console.log("User路由监听", route.pathname, type)
  })

 2.2 取消路由监听

取消路由监听:监听路由时会返回一个函数,调用函数即可取消监听,应该写在componentWillUnmount

2.3 在根组件app中监听路由

2.2.1.1, 在app.js中从路由模块导入withRouter

import { withRouter } from ‘react-router-dom’

 2.2.1.2, 导出App时,用withRouter 函数处理后导出, 把路由数据添加到props中

export default withRouter(App);

 2.2.1.3, 在app根组件的componentDidMount函数中添加全局路由监听

: 全局路由监听,根组件App中没有路由信息, 需要使用高阶组件withRouter添加路由信息,然后监听

2.4 局部路由监听

2.4.1在路由跳转的组件中使用props.history.listen() 监听路由, 得到返回值cancle

this.cancle = props.history.listen((route, type)=>{})

 2.4.2 在组件的componentWillUnmount中取消路由监听, 调用 cancle函数, 以防止重复监听,浪费性能

this.cancle()

 局部监听只能监听此组件离开时的路由, 类似于vue中beforeRouteLeave() 路由守卫

3.react路由过渡动画

3.1在react工程中下载安装过渡动画模板

npm install react-transition-group --save

 3.2在需要执行过渡的组件中导入动画模块

import { CSSTransition } from “react-transition-group”

 3.3 在需要过渡的标签外层添加CSSTransition组件


        
  • in:控制子元素显示隐藏的条件,一般是bool值或表达式
  • timeout:入场或出场动画的事件,单位默认是毫秒
  • classNames:入场或出场class属性名前缀

3.4 在组件的css中通过class设置入场和出场动画

.myfade-enter .myfade-enter-active .myfade-enter-done

.myfade-exit .myfade-exit-active .myfade-exit-done

注意:1,入场和出场的class样式要按顺序写,动画开始和结束顺序不能颠倒

​           2,需要在index.js中关闭严格模式,删除

          ​ 3,enter-active和exit-active中要写过渡结束状态才有效

 4.路由切换动画

4.1 在react工程中下载安装过渡动画模块

npm install react-transition-group --save

 4.2 在路由配置文件/src/router/index.js中导入动画组件

import { TransitionGroup, CSSTransition } from “react-transition-group”

4.3在路由组件模板中,用动画组件包裹路由组件

  
        
            
                
            
        
    

 CSSTransition组件的key属性要保证唯一性,所以用location.pathname Switch 组件要设置location属性为路由信息的props.location, 保证路由跳转组件的key和CSSTransition的key一致

4.4路由组件中没有路由信息location.pathname, 需要使用withRouter导入

import { withRouter } from "react-router-dom"
export default withRouter(MyRouter)

 

4.5在组件的css文件中写路由切换动画过程

/* 入场动画过程 */
.binge1-enter{
  transform: translateX(200px)
}
.binge1-enter-active{
  transition: 2s;
  transform: translateX(0px)
}
.binge1-enter-done{
  transform: translateX(0px)
}
/* 出场动画过程 */
.binge1-exit{
  transform: translateX(0px)
}
.binge1-exit-active{
  transition: 2s;
  transform: translateX(200px)
}
.binge1-exit-done{
  transform: translateX(200px)
}

.home, .user, .login, .animate{
  position: absolute;
  left: calc(50% - 200px)
}

转载他人CSDN。

你可能感兴趣的:(react.js,javascript,前端)