使用NextJS 13进行模态路由

8ehkhllq  于 2022-12-23  发布在  其他
关注(0)|答案(1)|浏览(214)

如何使用NextJS 13实现模态路由?以前使用屏蔽URL的as概念是可以实现的:

import { useRouter } from "next/router";

let router = useRouter();

<div>
  {router.query.image && <Modal />}
  <div>
    <Link href="/?image=1" as="/1">
      <a>
        <img src="/1.jpeg" />
      </a>
    </Link>
  </div>
</div>

现在as是一个遗留属性,不建议放在app目录中。

import { useSearchParams } from "next/navigation";

const searchParams = useSearchParams();
const image = searchParams.get("image");

<div>
  {image && <Modal />}
  <div>
    <Link 
      href={{
        pathname: "/",
        query: { image: 1 },
      }}
      // ----doesn't work now----
      as="/1">
        <img src="/1.jpeg" />
    </Link>
  </div>
</div>

我该怎么处理这个问题?太好了!

xsuvu9jc

xsuvu9jc1#

我没有收到此旧错误...请尝试以下操作:

    • 索引. js**
import Link from "next/link";
import { useRouter } from "next/router";

export default function Home() {
  let router = useRouter();

  return (
    <div>
      {router.query.image && (
        <div
          onClick={() => {
            router.push("/")
          }}
          style={{
            position: "fixed",
            top: "0px",
            left: "0px",
            width: "100%",
            height: "100%",
            textAlign: "center",
            background: "rgba(0,0,0, 0.6)",
            color: "white",
            fontSize: "50px",
          }}>
          <h1>
            {router.query.image}
          </h1>
        </div>
      )}
      <div style={{ display: "flex", alignItems: "start" }}>
        <Link style={{ border: "1px solid", padding: "30px", marginRight: "20px" }} href="/?image=1" as="/1">
          <h1>1</h1>
        </Link>
        <Link style={{ border: "1px solid", padding: "30px", marginRight: "20px" }} href="/?image=2" as="/2">
          <h1>2</h1>
        </Link>
        <Link style={{ border: "1px solid", padding: "30px", marginRight: "20px" }} href="/?image=3" as="/3">
          <h1>3</h1>
        </Link>
        <Link style={{ border: "1px solid", padding: "30px", marginRight: "20px" }} href="/?image=4" as="/4">
          <h1>4</h1>
        </Link>
        <Link style={{ border: "1px solid", padding: "30px", marginRight: "20px" }} href="/?image=5" as="/5">
          <h1>5</h1>
        </Link>
        <Link style={{ border: "1px solid", padding: "30px", marginRight: "20px" }} href="/?image=6" as="/6">
          <h1>6</h1>
        </Link>
      </div>
    </div>
  );
}

此文件用于处理直接在浏览器中访问url,而不是通过路由器(例如粘贴http://localhost:3000/5)

  • [图片]. js*
import { useRouter } from "next/router"
import { useEffect } from "react";

export default function () {
    const router = useRouter();
    useEffect(() => {
        if (!router.isReady) return;

        router.push(`/?image=${router.query.image}`, `/${router.query.image}`);

    }, [router.isReady]);

    return <></>
}

相关问题