跳转到内容

使用字典

字典是传统的键值翻译文件。它们适用于:

  • 在许多组件之间共享的字符串(按钮标签、错误消息)
  • 在代码库之外管理的内容
  • 从现有 i18n 配置迁移
{
"dictionaries": {
"include": ["src/dictionaries/*.json"],
"format": "key-value"
}
}
src/dictionaries/common.json
{
"save": "Save",
"cancel": "Cancel",
"delete": "Delete",
"loading": "Loading..."
}

useDictionary(filenameKey) 会查找一个字典文件,并返回一个 Record<string, string>。文件名键是去掉 .json 扩展名后的字典路径:

  • src/dictionaries/common.jsoncommon
  • src/dictionaries/pages/home.jsonpages/home
import { useDictionary } from 'tyndale-react';
export function ActionButtons() {
const labels = useDictionary('common');
return (
<div>
<button>{labels.save ?? 'Save'}</button>
<button>{labels.cancel ?? 'Cancel'}</button>
</div>
);
}

如果没有条目匹配该文件名键,useDictionary(filenameKey) 会返回一个空对象。