当前位置: 首页 > 文档资料 > Next.js 中文文档 >

高阶组件

优质
小牛编辑
125浏览
2023-12-01

Examples
  • Using the `withRouter` utility

如果你想应用里每个组件都处理路由对象,你可以使用withRouter高阶组件。下面是如何使用它:

import { withRouter } from 'next/router'

const ActiveLink = ({ children, router, href }) => {
  const style = {
    marginRight: 10,
    color: router.pathname === href? 'red' : 'black'
  }

  const handleClick = (e) => {
    e.preventDefault()
    router.push(href)
  }

  return (
    <a href={href} onClick={handleClick} style={style}>
      {children}
    </a>
  )
}

export default withRouter(ActiveLink)

上面路由对象的 API 可以参考next/router.