最佳实践
将 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 的更多信息。