You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何为input的placeholder添加i18next翻译?

react-i18next input placeholder翻译报错解决方法

你遇到的导入错误是因为t方法不支持直接从react-i18next顶层导出,需要通过官方提供的Hook或高阶组件获取,具体修改步骤如下:

函数组件修改方案

  • 修正导入语句,引入useTranslation Hook:
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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 15:39:02