英文:
Deno Fresh getting pathname
问题
我对deno和Fresh框架都不太熟悉(在Google上查找答案确实有点困难)。我想要使导航链接在与路径名匹配时具有不同的背景颜色。
这是我尝试过的代码:
const NavLink = ({ href, children }: NavLinkProps) => {
const isActive = location.pathname === href
const bgClass = isActive ? tw`bg-gray-900` : tw`bg-transparent`
return (
<a
href={href}
className={tw`px-3 py-2 rounded-md text-sm font-medium text-white ${bgClass}`}
>
{children}
</a>
)
}
但是location
是未定义的...
英文:
I'm quite new to deno and the Fresh framework (which is really hard to google for answers). I wanna make a nav link a different background color of it matches the pathname
this is what I tried:
const NavLink = ({ href, children }: NavLinkProps) => {
const isActive = location.pathname === href
const bgClass = isActive ? tw`bg-gray-900` : tw`bg-transparent`
return (
<a
href={href}
className={tw`px-3 py-2 rounded-md text-sm font-medium text-white ${bgClass}`}
>
{children}
</a>
)
}
But location
is undefined..
答案1
得分: 1
你可以从 PageProps.url
获取当前URL数据并传递给你的组件。
来自文档:
实际上,PageProps接口包含了许多有用的属性,可以用来自定义渲染输出。除了匹配的URL模式参数外,原始URL和路由名称也可以在这里找到。
const NavLink = ({ href, children, location }: NavLinkProps) => {
const isActive = location.pathname === href
const bgClass = isActive ? tw`bg-gray-900` : tw`bg-transparent`
return (
<a
href={href}
className={tw`px-3 py-2 rounded-md text-sm font-medium text-white ${bgClass}`}
>
{children}
</a>
)
}
export default function Page(props: PageProps) {
return (
<div>You are on the page '{props.url.href}'.
<NavLink href="/foo" children="Foo" location={props.url} />
</div>
)
}
英文:
You can get current URL data from PageProps.url
and pass it to your component.
From the docs
> The PageProps interface actually contains a bunch of useful properties
> that can be used to customize the rendered output. Next to the matched
> url pattern parameters, the raw url, and the route name can also be
> found in here.
const NavLink = ({ href, children, location }: NavLinkProps) => {
const isActive = location.pathname === href
const bgClass = isActive ? tw`bg-gray-900` : tw`bg-transparent`
return (
<a
href={href}
className={tw`px-3 py-2 rounded-md text-sm font-medium text-white ${bgClass}`}
>
{children}
</a>
)
}
export default function Page(props: PageProps) {
return (
<div>You are on the page '{props.url.href}'.
<NavLink href="/foo" children="Foo" location={props.url} />
</div>
)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论