您是否曾看過網站上的某個頁面,然後心想:「我們為什麼要載入這麼多 JavaScript?這個頁面上除了連結什麼都沒有!」對於 JavaScript 框架來說,這似乎有點奇怪,但您可以透過一個布林值輕鬆關閉 JavaScript,而您的資料載入、連結,甚至是表單仍然可以運作。
這是我們喜歡的做法
開啟您想要包含 JavaScript 的每個路由模組,並新增一個「handle」。這是一種讓您將關於路由的任何類型的元資訊提供給父路由的方法(您稍後會看到)。
export const handle = { hydrate: true };
現在開啟 root.tsx
,引入 useMatches
並新增以下內容
import {
Meta,
Links,
Scripts,
Outlet,
useMatches,
} from "@remix-run/react";
export default function App() {
const matches = useMatches();
// If at least one route wants to hydrate, this will return true
const includeScripts = matches.some(
(match) => match.handle?.hydrate
);
// then use the flag to render scripts or not
return (
<html lang="en">
<head>
<Meta />
<Links />
</head>
<body>
<Outlet />
{/* include the scripts, or not! */}
{includeScripts ? <Scripts /> : null}
</body>
</html>
);
}
您所有的資料載入仍然會在伺服器端渲染上運作,並且您所有的 <Link>
在底下都會渲染成正常的 <a>
,因此它們將繼續運作。
在任何頁面上,您隨時都可以在純 HTML 和完整的客戶端轉場之間切換。
如果您需要一小部分互動性,請使用 <script dangerouslySetInnerHTML>
。
return (
<>
<select id="qty">
<option>1</option>
<option>2</option>
<option value="contact">
Contact Sales for more
</option>
</select>
<script
dangerouslySetInnerHTML={{
__html: `
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('qty').onchange = (event) => {
if (event.target.value === "contact") {
window.location.assign("/contact")
}
}
});
`,
}}
/>
</>
);