如何在 TanStack Start v1 中设置文档语言

为浏览器和屏幕阅读器声明页面语言

问题

网页必须声明其主要语言,以确保在不同用户代理中正常运行。如果根 HTML 元素没有明确声明语言,浏览器无法判断内容所用的语言,只能进行猜测。这会导致屏幕阅读器默认使用用户系统语言,从而在内容语言不一致时产生错误发音。由于缺乏源语言信息,浏览器也无法提供准确的翻译功能。搜索引擎难以将内容准确地索引到对应语言的受众,降低了该语言用户的可发现性。

解决方案

lang 属性添加到 html 标签上,以设置页面的默认语言。在 TanStack Start 中,HTML shell 在根路由的 shellComponent 中定义,该文件负责渲染文档结构,包括 <html> 元素。通过为该元素添加带有合适语言代码的 lang 属性,可以让浏览器、辅助技术和搜索引擎正确识别内容语言,从而实现正确的处理和展示。

步骤

1. 确定当前语言环境

根路由的 shellComponent 属性定义了包裹所有路由内容的 HTML shell,并始终在服务端渲染。请根据应用的语言检测机制(如路由参数、Cookie 或请求头)确定当前的语言环境。

import type { ReactNode } from "react";
import {
  Outlet,
  createRootRoute,
  HeadContent,
  Scripts,
} from "@tanstack/react-router";

export const Route = createRootRoute({
  shellComponent: RootDocument,
  component: RootComponent,
});

function RootComponent() {
  return <Outlet />;
}

function RootDocument({ children }: { children: ReactNode }) {
  const locale = "en";

  return (
    <html>
      <head>
        <HeadContent />
      </head>
      <body>
        {children}
        <Scripts />
      </body>
    </html>
  );
}

这将建立你需要添加语言属性的 shell 结构。

2. 为 html 元素添加 lang 属性

使用本地化值在 lang 属性中设置 <html> 元素。请使用符合内容语言的有效 BCP 47 语言标签。

function RootDocument({ children }: { children: ReactNode }) {
  const locale = "en";

  return (
    <html lang={locale}>
      <head>
        <HeadContent />
      </head>
      <body>
        {children}
        <Scripts />
      </body>
    </html>
  );
}

lang 属性现在声明了文档语言,使浏览器和辅助技术能够正确处理内容。

3. 使用动态本地化值

如果您的应用支持多种本地化语言,请从路由或状态管理系统中获取当前本地化值,并将其传递给 shell 组件。

function RootDocument({ children }: { children: ReactNode }) {
  const locale = getCurrentLocale();

  return (
    <html lang={locale}>
      <head>
        <HeadContent />
      </head>
      <body>
        {children}
        <Scripts />
      </body>
    </html>
  );
}

function getCurrentLocale(): string {
  return "en";
}

文档语言现在会根据当前本地化值动态更新,确保 lang 属性始终反映当前内容语言。