0

我有一个下拉菜单,其中列出了选项 1、选项 2 和选项 3。我想使用 react-i18next 翻译这些选项。我是翻译和使用这个框架的新手。

下面是代码,

export default class Example extends React.Component {
    render() {
        return (
            <ParentComponent>
                <button type="button">
                    {this.props.placeholder}
                </button>
                {this.props.values.map(value => (
                    <Item
                        key={value[this.props.value_prop]}
                        value={value}
                        on_select={this.change}>
                        {value[this.props.label_prop]} // i want to 
                        translate this
                    </Item>
                ))}
            </ParentComponent>
        );
}

有人可以提供有关如何解决此问题的想法...或帮助我解决此问题。谢谢。

4

1 回答 1

1

react-i18next包含很好的文档,他们还提供了一些示例

您基本上需要将组件包装在withTranslation包装器中并使用t道具:

import { useTranslation, withTranslation, Trans } from 'react-i18next';
import logo from './logo.svg';
import './App.css';

// use hoc for class based components
class LegacyWelcomeClass extends Component {
  render() {
    const { t, i18n } = this.props;
    return <h2>{t('title')}</h2>;
  }
}
const Welcome = withTranslation()(LegacyWelcomeClass);

您尚未发布完整的组件代码,但它应该如下所示:

class CompClass extends Component {
    render() {
        const { t, i18n } = this.props;
        return (
            <ParentComponent>
                <button type="button">
                    {this.props.placeholder}
                </button>
                {this.props.values.map(value => (
                    <Item
                        key={value[this.props.value_prop]}
                        value={value}
                        on_select={this.change}>
                        {t(value[this.props.label_prop])} // i want to translate this
                    </Item>
                ))}
            </ParentComponent>
        );
    }
}

const Comp = withTranslation()(CompClass);
于 2019-06-04T11:36:45.470 回答