繁体   English   中英

如何使用<Trans />用于替代图像翻译的 react-i18next?

[英]How to use <Trans /> of react-i18next for an alt image translation?

我有一个问题应该(希望)很容易解决。 我已经在我的项目中安装了react-i18next并且一切正常,我能够在功能组件中进行翻译,在类中,但我现在唯一的问题是在类组件中,特别是关于 html 属性,我正在谈论图像的 alt。

// ...
import { Translation, Trans } from 'react-i18next'

class MyComponent extends Component<MyComponentProps, MyComponentState> {
  constructor(props: MyComponentProps) {
    super(props)

    this.state = {
      isButtonVisible: true,
      isAnimationVisible: false,
      deadline: 0,
      countdown: ''
    }

    // ...
  }

  // ...

  render () {
    const { isButtonVisible, isAnimationVisible, deadline } = this.state

    return (
      <>
        <Trans>
          <img className={styles.exercise} src={lungs} alt={`${t('animation.lungs')} IDXXX`}  />
        </Trans>
      <>
    )
  }
}

其中animation.lungs是我在语言环境文件中的翻译,IDXXX 是不需要任何翻译的数字 ID。

t 没有定义,它是有道理的,但这里的文档对我来说不清楚https://react.i18next.com/legacy-v9/trans-component 你有什么想法如何解决吗?

提前致谢

您可以导入withTranslation HOC 以访问t()

import { Translation, Trans, withTranslation, WithTranslation } from 'react-i18next'

type MyComponentProps = {} & WithTranslation

class MyComponent extends Component<MyComponentProps, MyComponentState> {
  constructor(props: MyComponentProps) {
    super(props)

    this.state = {
      isButtonVisible: true,
      isAnimationVisible: false,
      deadline: 0,
      countdown: ''
    }

    // ...
  }

  // ...

  render () {
    const { isButtonVisible, isAnimationVisible, deadline } = this.state
    const { t } = this.props;

    return (
      <>
        <Trans>
          <img className={styles.exercise} src={lungs} alt={`${t('animation.lungs')} IDXXX`}  />
        </Trans>
      <>
    )
  }
}

export default withTranslation()(MyComponent)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM