最佳实践
将 URL 放入变量中
在翻译包含 URL 或类似数据的字符串时,推荐的做法是将这些 URL 放入变量中,然后在模板内引用它们。
<Translate
string={`Click <a href="{{url}}">here</a>`}
variables={{url: 'https://tacotranslate.com'}}
/>
使用 ARIA 标签
在翻译诸如按钮之类的交互元素文本时,包含 ARIA 标签以确保无障碍访问非常重要。ARIA 标签帮助屏幕阅读器提供有关元素功能的描述信息。
例如,如果您有一个允许用户从代码块中复制文本的按钮,可以使用 aria-label
属性来提供明确的描述:
<Translate
aria-label={useTranslation('Copy to clipboard')}
string="Copy"
/>
这件事感觉有点元。
全局来源数组和多个组件来源
此模式仅适用于使用 Next.js Pages Router 时。
在处理大型应用程序时,将字符串和翻译拆分成多个较小的来源是有益的。这种方法有助于减少包的大小和传输时间,确保本地化的高效性和可扩展性。
虽然在仅在客户端渲染时这很简单,但在为服务器端渲染获取翻译时,管理来源会迅速变得复杂。不过,您可以通过使用 TacoTranslate 客户端的 origins
数组来自动管理来源。
请考虑这个示例,我们已将组件和页面拆分到不同的文件中。
components/pricing-table.tsx
import TacoTranslate, {Translate} from 'tacotranslate/react';
import tacoTranslate from '../tacotranslate-client';
// Set an origin name for this component
const origin = 'components/pricing-table';
// Push the origin into the origins array as this file is imported
tacoTranslate.origins.push(origin);
export default function PricingTable() {
return (
<TacoTranslate origin={origin}>
<Translate string="Pricing table" />
// ...
</TacoTranslate>
);
}
pages/pricing.tsx
import TacoTranslate, {Translate} from 'tacotranslate/react';
import getTacoTranslateStaticProps from 'tacotranslate/next/get-static-props';
import tacoTranslateClient from '../tacotranslate-client';
import PricingTable from '../components/pricing-table';
const origin = 'pages/pricing';
tacoTranslateClient.origins.push(origin);
export default function PricingPage() {
return (
<TacoTranslate origin={origin}>
<Translate string="Pricing page" />
<PricingTable />
</TacoTranslate>
);
}
// We will now fetch translations for all imported components and their origins automatically
export async function getStaticProps(context) {
return getTacoTranslateStaticProps(context, {client: tacoTranslateClient});
}
查看我们的服务器端渲染示例,了解有关 getTacoTranslateStaticProps
的更多信息。