模拟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)
    }
})