从列表中选择第一个选项作为默认选项

时间:2018-09-06 03:50:56

标签: reactjs react-native

我是React native的新手。我正在为我的项目使用语言翻译模块。以下代码可以正常工作,但我希望将英语作为默认语言。现在我开始显示“选择语言”。

这是我尝试过的代码。

const language = [
    { lang: "English", code: "en" },
    { lang: "French", code: "fr" }
]

class CounterApp extends Component {
    constructor() {
        super();
        this.state = {
            languages: [],
            value: false,
            langValue: "en",
            select: "Select Language",
        }
        this.onLanguage = this.onLanguage.bind(this);
    }
    onSelectLanguage = () => {
        return (
            language.map((data, i) => {
                return (
                    <View key={i} style={styles.dropDownView}>
                        <TouchableOpacity onPress={() => this.onSelectedLang(data)}>
                            <Text style={styles.dropDownText}>{data.lang}</Text>
                        </TouchableOpacity>
                    </View>
                )
            })
        )
    }

    onSelectedLang = (text) => {
        this.setState({
            value: false,
            select: text.lang,
        }),
            I18n.locale = text.code;
    }
    onLanguage = () => {
        this.setState({
            value: true,
        })
    }

    render() {
        return (
            <View style={styles.container}>
                <View>
                    <TouchableOpacity onPress={this.onLanguage}>
                        <View style={styles.buttonView}>
                            <Text style={styles.buttontext}>{this.state.select}</Text>
                        </View>
                    </TouchableOpacity>
                    <View>
                        {(this.state.value) ? this.onSelectLanguage() : null}
                    </View>
                </View>
            </View>
        );
    }
}

1 个答案:

答案 0 :(得分:0)

首先在构造函数中执行此操作

languages = [
    {id: 0, value: I18n.t('language_english'), locale: 'en'},
    {id: 1, value: I18n.t('language_hindi'), locale: 'hi'},
]


 constructor(props: Props) {
    super(props)
    I18n.locale = this.languages[0].locale
    this.state = {
        selectedLanguage: this.languages[0],
    }
}