React Typescript音乐播放器项目笔记:5、除Link外控制路由跳转:withRouter & typescript

19 篇文章 0 订阅
17 篇文章 0 订阅

项目地址https://github.com/BUPTlhuanyu/react-music-lhy

withRouter在typescript下的使用

利用react-router4官方提供的的withRouter进行路由跳转,在项目引入:

import {  Route, withRouter } from 'react-router'

然后利用withRouter包裹组件:

class SingerBase extends Component<singerProps, singerState>{
	...
}
const Singer = withRouter(SingerBase as any);

export default Singer

接口singerProps中应该加上接口属性history,类型这里设置为any,更严格的,通过查找react-router对应的声明文件d.ts(node_module/@types/react-router/inde.d.ts文件)中可以找到history对应的类型如下:

export interface RouterProps {
  history: H.History;
}

因此接口singerProps可定义为:

interface singerProps{
    history: any
}

或者:

import {RouterProps} from "react-router"
interface singerProps{
    history: RouterProps["history"]
}

控制路由跳转

在SingerBase组件中的方法控制路由跳转:

class SingerBase extends Component<singerProps, singerState>{
	...

	selectSinger = (singer:SingerClass) => {
   		this.props.history.push(`/somepath`);
	}

	render(){
		return (...)
	}
}

其他方法

1、利用react-router中的

2、利用this.context.router.history.push(’/somepath’)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值