关于withRouter的原理和用法

高阶组件中的withRouter, 作用是将一个组件包裹进Route里面, 然后react-router的三个对象history, location, match就会被放进这个组件的props属性中.

 

// withRouter实现原理: 
// 将组件包裹进 Route, 然后返回
// const withRouter = () => {
//     return () => {
//         return <Route component={Nav} />
//     }
// }

// 这里是简化版
const withRouter = ( Component ) => () => <Route component={ Component }/>

上面是实现的原理, react-router-dom 里面是有这个组件的, 直接引入使用就可以了

 

import React from 'react';
import { withRouter } from 'react-router-dom';

import './style.scss';
import { playCountConversion } from '../../../utils/utils';

class HomeSongList extends React.Component{
    render() {
        return (
            <div className='home-song-list clearfix'>
                {this.props.songList.map((item, index) => {
                    return (
                        <div className="home-song-item" key={index} onClick={() => {this.props.history.push('/playList/' + item.id)}}>
                            <img src={item.picUrl + '?param=200y200'} alt=""/>
                            <p>{item.name}</p>
                            <div className="headset-icon">{playCountConversion(item.playCount)}</div>
                        </div>
                    );
                })}
                
            </div>
        );
    }
}

export default withRouter(HomeSongList);

所以withRouter的作用就是, 如果我们某个东西不是一个Router, 但是我们要依靠它去跳转一个页面, 比如点击页面的logo, 返回首页, 这时候就可以使用withRouter来做.
在这个例子中, 我将span使用withRouter作为一个可点击跳转的Link



 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值