获取Deno Fresh的路径名

huangapple go评论69阅读模式
英文:

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) =&gt; {
  const isActive = location.pathname === href
  const bgClass = isActive ? tw`bg-gray-900` : tw`bg-transparent`

  return (
    &lt;a
      href={href}
      className={tw`px-3 py-2 rounded-md text-sm font-medium text-white ${bgClass}`}
    &gt;
      {children}
    &lt;/a&gt;
  )
}

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) =&gt; {
  const isActive = location.pathname === href
  const bgClass = isActive ? tw`bg-gray-900` : tw`bg-transparent`

  return (
    &lt;a
      href={href}
      className={tw`px-3 py-2 rounded-md text-sm font-medium text-white ${bgClass}`}
    &gt;
      {children}
    &lt;/a&gt;
  )
}

export default function Page(props: PageProps) {
  return (
    &lt;div&gt;You are on the page &#39;{props.url.href}&#39;.
      &lt;NavLink href=&quot;/foo&quot; children=&quot;Foo&quot; location={props.url} /&gt;
    &lt;/div&gt;
  )
}

huangapple
  • 本文由 发表于 2023年5月25日 16:44:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76330393.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定