码迷,mamicode.com
首页 > 其他好文 > 详细

模拟vue的tag属性,在react里实现自定义Link

时间:2018-11-18 16:12:59      阅读:442      评论:0      收藏:0      [点我收藏+]

标签:location   goto   ext   ===   path   class   redirect   link   weight   

我封装了一个简单的实现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>
    )
  }
}

 

模拟vue的tag属性,在react里实现自定义Link

标签:location   goto   ext   ===   path   class   redirect   link   weight   

原文地址:https://www.cnblogs.com/kaiqinzhang/p/9977992.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!