react-native google translater

时光怂恿深爱的人放手 提交于 2021-02-10 14:51:57

问题


I have developed an android mobile app using react-native. My native language for the app is English but I want to make it available in Mandarin Chinese also. So my question is how can I convert my static and fetched data into Mandarin Chinese. please share a solution.


回答1:


Yes, you can do it. For changing the Application language to multi-language app,i.e., also include Mandarin Chinese.

  1. For Static contents/text Use the package react-native-i18n

Link : https://www.npmjs.com/package/react-native-i18n

  1. For Dynamic contents/text use the package google-translate-api

Link :https://www.npmjs.com/package/google-translate-api

I18n Example :

import I18n from 'react-native-i18n';

class Demo extends React.Component {
  render() {
    return <Text>{I18n.t('greeting')}</Text>;
  }
}

// Enable fallbacks if you want `en-US` and `en-GB` to fallback to `en`
I18n.fallbacks = true;

I18n.translations = {
  en: {
    greeting: 'Hi!',
  },
  fr: {
    greeting: 'Bonjour!',
  },
};

Google-translator Example:

From automatic language detection to English:

const translate = require('google-translate-api');

translate('Ik spreek Engels', {to: 'en'}).then(res => {
    console.log(res.text);
    //=> I speak English
    console.log(res.from.language.iso);
    //=> nl
}).catch(err => {
    console.error(err);
});

From English to Dutch with a typo:

translate('I spea Dutch!', {from: 'en', to: 'nl'}).then(res => {
    console.log(res.text);
    //=> Ik spreek Nederlands!
    console.log(res.from.text.autoCorrected);
    //=> true
    console.log(res.from.text.value);
    //=> I [speak] Dutch!
    console.log(res.from.text.didYouMean);
    //=> false
}).catch(err => {
    console.error(err);
});

Hope it helps..! Thank you

~ Praz




回答2:


You would need to refactor your codebase in some manner.
First of all, if your static data is stored as hardcoded you need to refactor.

I suggest using https://github.com/react-native-community/react-native-languages
Example for your inspiration is located here.

Now the second part, where you need dynamic translation.

First of all, you need the current user language which is accessible with the beforementioned package.
Then use a package like google-translate-api to translate on the fly.



来源:https://stackoverflow.com/questions/53701231/react-native-google-translater

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!