React中如何为input的placeholder添加i18next翻译?
react-i18next input placeholder翻译报错解决方法
你遇到的导入错误是因为t方法不支持直接从react-i18next顶层导出,需要通过官方提供的Hook或高阶组件获取,具体修改步骤如下:
函数组件修改方案
- 修正导入语句,引入
useTranslationHook:
import { useTranslation, Trans } from "react-i18next";
- 在组件内部调用Hook获取
t方法后使用:
const YourComponent = () => { const { t } = useTranslation(); return ( <> {/* 原有Trans组件用法不需要修改 */} <Trans i18nKey="item.key">Fallback text</Trans> {/* placeholder正常使用t方法翻译 */} <input placeholder={t('input.placeholder')} /> </> ) }
类组件修改方案
如果使用类组件无法调用Hook,可以使用withTranslation高阶组件注入t方法:
import { withTranslation, Trans } from "react-i18next"; import React from "react"; class YourComponent extends React.Component { render() { const { t } = this.props; return ( <> <Trans i18nKey="item.key">Fallback text</Trans> <input placeholder={t('input.placeholder')} /> </> ) } } export default withTranslation()(YourComponent);
注意事项
- 请确保对应语言资源文件中已经配置了
input.placeholder键对应的翻译内容 - 原有
<Trans>组件的使用逻辑无需做任何修改,可正常运行
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

