useT hook
使用 useT hook 翻译 props 中的字符串和属性,例如按钮的 aria-label。
import { useT } from '@magic-translate/react';const MyComponent = () => {const t = useT();return (<button aria-label={t('Main menu')}><HamburgerIcon /></button>);};
你可以在组件内的任何地方使用 t() 函数。如果你愿意,你也可以在标记中使用它而不是 <T> 组件。
const MyComponent = () => {const t = useT();return <p>{t('This will be translated')}</p>;};
变量
要将名称或计数等值放入字符串中,请调用 t 作为带标签的模板,不带括号:
const MyComponent = ({ count }: { count: number }) => {const t = useT();return <p>{t`You have ${count} unread messages`}</p>;};
Magic Translate 对 You have {0} unread messages 进行一次翻译,然后将该值放回您的应用程序中,因此每次计数都需要一个缓存的翻译。这些值永远不会发送到 Magic Translate。这与 <T> 组件中的 v() 相同。
选项
您可以向 t() 传递与 <T> 组件相同的选项,例如 formality。
const MyComponent = () => {const t = useT();return <button>{t('Please click here', { formality: 'formal' })}</button>;};
这包括 id,用于自行编辑文本的这种用法:
<button aria-label={t('Save', { id: 'checkout-save' })} />
带标签的模板不带任何选项。对于同时包含变量和 id 的文本,使用 <T> 组件。