在react-bootstrap select输入中显示选择的i18next语言

import React from 'react';
import i18n from "i18next";
import { withTranslation,WithTranslation } from 'react-i18next';
import {Form} from 'react-bootstrap';

interface State {
    language: string;
}

interface Props extends WithTranslation {}

class LanguageSwitcher extends React.Component<WithTranslation,State,Props> {

    constructor(props: Props) {
        super(props);
        this.state = {
            language: 'en'
        };
    }

    changeLang = async (event: any) => {
        i18n.changeLanguage(event.target.value);
        this.setState({...this.state,language: event.target.value});
        await new Promise(r => setTimeout(r,200));
    }

    render() {
        const { t,i18n } = this.props;
        const getcurrentLng = () => i18n.language || window.localStorage.i18nextLng || '';

        return (
            <div classname="tmf-language-switcher">
                <Form>
                    <Form.Group controlId="form-language">
                        <Form.Label>{t('language')}</Form.Label>
                        <Form.Control value={this.state.value} as="select" onChange={this.changeLang.bind(this)} ref="valid_for">
                            <option value="en">{t('English')}</option>
                            <option value="de">{t('German')}</option>
                        </Form.Control>
                    </Form.Group>
                </Form>
            </div>
        );
    }
}

export default withTranslation()(LanguageSwitcher);

我正在使用react-i18next和react-bootstrap来实现语言切换器。

上面的代码可以工作,并且我可以切换语言,但是如果我更改路线并返回,则在控制选项中未选择当前语言。

有人可以告诉我,如何显示正确的默认语言?

chen192 回答:在react-bootstrap select输入中显示选择的i18next语言

我通过将getCurrentLng()作为value传递到我的Form.Control来解决了这个问题:

  

<Form.Control value={getCurrentLng()} as="select" onChange={this.changeLang.bind(this)}>

本文链接:https://www.f2er.com/3119437.html

大家都在问