高阶组件
优质
小牛编辑
125浏览
2023-12-01
- 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
.