react-i18next如何使用 进行alt图像翻译?

问题描述 投票:0回答:1

我有一个问题,应该(希望)简单解决。我已经在项目中安装了react-i18next,并且一切正常,我能够在类中的Functional组件中进行翻译,但是现在我唯一的问题是在类组件中,特别是关于html属性,我在说图片的高度。

// ...
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。您有任何解决方法的想法吗?

提前感谢

javascript reactjs translation jsx i18next
1个回答
0
投票

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

import { Translation, Trans, withNamespaces } 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
    const { t } = this.props;

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

export default withNamespaces(MyComponent);
© www.soinside.com 2019 - 2024. All rights reserved.