zoukankan      html  css  js  c++  java
  • 模拟vue的tag属性,在react里实现自定义Link

    我封装了一个简单的实现react里自定义Link的方法,方便大家使用。

     

    因为普通组件没有metch、location、history等属性。只有在<Router>里面的<component>渲染的组件才有那三个属性。所以我定义了一个组件,写<Route>来是实现 自定义Link。
    class
    CustomNavLink extends Component{ render(){ return( <Route children={({match,location,history})=>{ return( <li onClink={this.goto.bind(this,history,props.to)}> //通过点击事件来进行跳转。我这里是<li>标签,你可以换成你需要的。 { location.pathname===thiss.props.to?">"+this.props.children:this.props.children //这里写标签里的内容,我这里是实现的是一个点击标签,给当前标签添加一个“>”来标识。 } </li> ) }} > ) } goto(history,to){ //模拟vue里的tag的点击事件 history.push(to) } }

    这里是我引用上面组件的一个例子,大家可以参考一下。

    class Home extends Component {
      render () {
        return (
          <div>
             <ul>
                <CustomNavLink to="/food">food</CustomNavLink>
                <CustomNavLink to="/wiki">wiki</CustomNavLink>
                <CustomNavLink to="/profile">profile</CustomNavLink>
            </ul>
            <Switch>
             <Redirect from="/" exact to="/food" />
             <Route path="/food" component={Food} />
             <Route path="/wiki" component={Wiki} />
             <Route path="/profile" component={Profile} />
             <Route component={Page404}/>
            </Switch>
         </div>
        )
      }
    }

    但是吧上面自定义Link的方法也有不足之处,还要定义一个<Route>,接下来我们通过withRouter这个方法来让一个普通组件带上路由的状态信息。

    先来简单介绍一下withRouter:把一个组件放进去,就能给它history等属性。

    下面是实现的代码:

    const CustomNavLink = withRouter(class EnhanceCustomNavLink extends Component {
       render () {
         return (
            <li onClick={this.goto.bind(this)}>
               {
                    this.props.location.pathname === this.props.to ? '>' + this.props.children : this.props.children    //这里面的内容根据你的需求自己写
               }
            </li>
           )
       }
    
        goto () {
              this.props.history.push(this.props.to)
        }
    })
  • 相关阅读:
    微引擎的自定义菜单40063错误解决
    jquery 重复事件
    信号量机制DOWN操作和UP操作的详细说明
    每日算法37:Rotate Image (图像旋转)
    讨论嵌入式系统测试方案
    Android 从硬件到应用程序:一步一步爬上去 6 -- 我写的APP测试框架层硬件服务(终点)
    MVC 接受Flash上传图片
    autorun.vbs病毒的清除办法
    【行业翘楚】井田云:化解线上线下冲突让鱼与熊掌皆得
    Tuxedo入门学习
  • 原文地址:https://www.cnblogs.com/kaiqinzhang/p/9977992.html
Copyright © 2011-2022 走看看