反应本机句柄翻译和语言

时间:2018-05-03 13:21:43

标签: javascript reactjs react-native translation

你如何处理反应原生的翻译?这就是我做到的。这是不好的编码风格还是性能不好?

Language.js

export default {
    appName: "TestApp",
    welcome: {
        header: {
            title: (l) => {
                switch (l) {
                    case "de": return `germanTitle`
                    case "en": return `englishTitle`
                }
            },
            subtitle: (l) => {
                switch (l) {
                    case "de": return `germanSubtitle`
                    case "en": return `englishSubtitle`
                }
            }
        }
    }
}

然后在我的应用中

import language from "./language.js"
let lang = "de"
...

render(){
    return (
        <View>
            <Text>{language.welcome.title(lang)}</Text>
        </View>
    )
}

4 个答案:

答案 0 :(得分:2)

目前在我们的项目中,我们正在使用this repo :) 请记住,如果您正在使用Expo

,则需要弹出

答案 1 :(得分:0)

尝试使用I18n。我已经使用它并在很大程度上定制它。它工作得非常好,并提供您的应用程序将来可能需要的更多。我将尝试在git上使用I18n添加一个示例,并将评论该链接。但是现在你可以使用自己的逻辑。

答案 2 :(得分:0)

我通过使用Redux和AsyncStorage在this repo中制定了自己的解决方案,因为我必须在应用程序中更改语言。该实现使用Expo作为CLI,但与Expo没有任何关系。这是一个实现的想法,而不是现成的库;)。

答案 3 :(得分:0)

我创建了一个小库来处理React中的翻译。

https://www.npmjs.com/package/react-littera

您只需在组件内部添加带有翻译的对象,或从文件中导入它即可。

以下是使用类组件的示例

import React from "react";
import { Text } from "react-native";

import { withLittera } from "react-littera";

// Regular JS object with your translations. 
// Can also be placed in another file and just simply imported here.
const translations = {
    title: {
        en_US: "This is a title",
        pl_PL: "To jest tytuł",
        de_DE: "Dies ist ein Titel"
    },
    subtitle: {
        en_US: "This is a subtitle",
        pl_PL: "To jest podtytuł",
        de_DE: "Dies ist ein Untertitel"
    }
};

class ExampleComponent extends React.Component {
    render() {
        const { translated } = this.props; // An object called "translated" is passed with props.

        // This is how you display a translated string.
        return <Text>{translated.title}</Text>;
    }
}

export default withLittera(translation)(ExampleComponent); // <- Here you pass the translations to the withLittera HOC.

我已经在很多项目中使用了该库,它似乎运行良好。请记住使用 LitteraProvider 包装您的应用,并将有效的语言值和语言更改回调传递给它。

PS。该库实际上是用于React的,但似乎可以与React Native一起使用。

相关问题