[英]How to disable React link and function if link points to current active “page”
我有一個包含鏈接列表的導航組件。 除了鏈接(轉到特定頁面)之外,我還需要在單擊這些函數時運行一個函數。 到目前為止,我的工作是正常的,除非用戶單擊指向活動頁面的鏈接。
如果用戶已經在該頁面上,如何修改我的代碼,以使我的功能無法運行並且鏈接被禁用?
這是我所擁有的:
class HeaderMenu extends Component {
navFunc = () => {
//some functionality
}
render() {
return (
<div>
<div className="sidebar">
<ul className="header">
<li onClick={this.navFunc}>
<Link href="/index">
<a>home</a>
</Link>
</li>
<li onClick={this.navFunc}>
<Link href="/about">
<a>about</a>
</Link>
</li>
<li onClick={this.navFunc}>
<Link href="/other">
<a>other</a>
</Link>
</li>
</ul>
</div>
</div>
)
}
}
您可以創建一個ActiveLink
組件,在單擊該組件時將跳過推送操作。
該ActiveLink
組件基於next.js文檔中的示例(向上滾動以查看它),而我尚未對其進行測試。
import { withRouter } from 'next/router'
const ActiveLink = ({ children, router, href }) => {
const active = router.pathname === href
const style = {
marginRight: 10,
color: active ? 'red' : 'black'
}
const handleClick = (e) => {
e.preventDefault()
active || router.push(href)
}
return (
<a href={href} onClick={handleClick} style={style}>
{children}
</a>
)
}
export default withRouter(ActiveLink)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.