禁用 JavaScript

禁用 JavaScript

¥Disabling JavaScript

你是否曾在网站上查看某个页面时想过“我们为什么要加载所有这些 JavaScript?”这个页面上除了链接什么都没有!这对于 JavaScript 框架来说可能有点奇怪,但你可以使用布尔值关闭 JavaScript,你的数据加载、链接甚至表单仍然会正常工作。

¥Do you ever look at a page on your site and think "why are we loading all of this JavaScript? There's nothing on this page but links!" This may seem a little odd for a JavaScript framework, but you can turn off JavaScript with a boolean and your data loading, links, and even forms will still work.

以下是我们喜欢的做法:

¥Here's how we like to do it:

打开你想要包含 JavaScript 的每个路由模块并添加 handle。这是一种向你的父路由提供任何关于路由元信息的方法(你稍后会看到)。

¥Open up each route module you want to include JavaScript for and add a handle. This is a way for you to provide any kind of meta-information about a route to the parent route (as you'll see in a moment).

export const handle = { hydrate: true };

现在打开 root.tsx,导入 useMatches 并添加以下内容:

¥Now open root.tsx, bring in useMatches and add this:

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> 中进行,因此它们将继续工作。

¥All of your data loading will still work on the server render, and all of your <Link>s render normal <a> underneath, so they will continue to work.

在任何页面上,你可以随时在纯 HTML 和完整的客户端转换之间切换。

¥On any page, at any time, you can flip between plain HTML and full client-side transitions.

如果你需要一点点交互,请使用 <script dangerouslySetInnerHTML>

¥If you need one tiny bit of interactivity, use a <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")
              }
            }
          });
        `,
      }}
    />
  </>
);
Remix v2.17 中文网 - 粤ICP备13048890号