React.js中如何用react-i18next翻译TextInput的占位符?
问题
已完成标签翻译且运行正常,相关导入及初始化代码如下:
import { useTranslation } from 'react-i18next'; const { t, ready } = useTranslation(['accountDetails']);
请问如何将以下TextInput组件中的英文占位符翻译成中文?
<TextInput mb={'sm'} label={t('first-name')} placeholder='First Name'{...form.getInputProps('firstName')} />
解决方案
- 在你的
accountDetails翻译资源文件(如accountDetails.json)中添加占位符对应的中文翻译条目,示例如下:
{ "first-name": "名字", "first-name-placeholder": "请输入名字" }
(键名可根据你的命名规范调整,只要和后续调用保持一致即可)
- 修改TextInput组件的
placeholder属性,通过t()函数调用对应的翻译键:
<TextInput mb={'sm'} label={t('first-name')} placeholder={t('first-name-placeholder')} {...form.getInputProps('firstName')} />
另外,建议在ready状态为true时再渲染组件,避免出现未翻译的原始文本:
if (!ready) return <div>加载中...</div>; return ( <TextInput mb={'sm'} label={t('first-name')} placeholder={t('first-name-placeholder')} {...form.getInputProps('firstName')} /> );
内容的提问来源于stack exchange,提问作者Nikitha
相关产品推荐
相关产品推荐

