用React中的自定义组件模拟实现Vue-router中tag功能

  我们在使用react-router-dom时,跳转链接的<List>会转换成<a>标签。由于<a>标签会破坏我们的布局,所以今天我用React中的自定义组件实现一个类似Vue中路由跳转中tag的功能,保留我们本来的标签。

  本篇文章涉及到的知识点包括:高阶组件withRouter,和Route组件的属性children。

Route方法实现过程如下:

class MyList extends Component{
    render(){
        return(
            <Route children={({match,history,location})=>{
                return (
                    <li onClick={this.jump.bind(this,history,this.props.to)}>
                        {location.pathname===this.props.to ? '>'+this.props.children:this.props.children}
                    </li>
                )
            }}>
            </Route>           
        )
    }
    jump(history,to){
        history.push(to)
    }
} 

 withRouter实现过程如下

const MyList = withRouter(
    class EnhenceList extends Component{
        render(){
            return(
                <li onClick={this.jump.bind(this)}>
                    {this.props.location.pathname===this.props.to ? '>'+this.props.children:this.props.children}
                </li>
            )
        }
        jump(){
            this.props.history.push(this.props.to)
        }
    }
) 

  

 

猜你喜欢

转载自www.cnblogs.com/ruchang/p/9971904.html
今日推荐