如何在 TanStack Start v1 中设置文档语言
为浏览器和屏幕阅读器声明页面语言
问题
网页必须声明其主要语言,以便在不同的用户代理中正常运行。如果根 HTML 元素上没有明确的语言声明,浏览器无法确定内容的语言,只能进行猜测。这会导致屏幕阅读器默认使用用户的系统语言,当内容语言不同于系统语言时,会导致发音错误。由于缺乏源语言信息,浏览器无法提供准确的翻译功能。搜索引擎在为适当的语言受众索引内容时会遇到困难,从而降低了用户在该语言中搜索时的可发现性。
解决方案
在 html 标签中添加一个 lang 属性,以设置页面的默认语言。在 TanStack Start 中,HTML 外壳在根路由的 shellComponent 中定义,该组件渲染包括 <html> 元素在内的文档结构。通过在此元素中添加带有适当语言代码的 lang 属性,可以告知浏览器、辅助技术和搜索引擎内容的语言,从而使它们能够正确处理和呈现内容。
步骤
1. 确定当前的区域设置
根路由的 shellComponent 属性定义了包裹所有路由内容的 HTML 外壳,并始终由服务器端渲染。通过应用程序的区域设置检测机制(如路由参数、cookies 或 headers)确定当前的区域设置。
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>
);
}
这建立了外壳结构,您将在其中添加语言属性。
2. 为 html 元素添加 lang 属性
在 <html> 元素上使用区域设置值设置 lang 属性。使用与内容语言匹配的有效 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 属性始终反映当前内容语言。