简体   繁体   中英

How to translate dynamically properties of an array of objects with i18n?

I have an array of objects each object have 2 properties (title and subtitle) and i want that the 2 properties have different type of translation depending on the video.So each video must have 3 different type of language translation and different strings.

For example the first object has title: 'cat', subtitle: 'purr' and the translation for example in Italian title: 'gatto', subtitle: 'miao', the second object has title: 'dog', subtitle: 'woof' and its current Italian translation.

I used i18n for the translations of the languages in the navigator and it worked but how can I do with this situation I described?

Here is my code of the cards of each videos if it can helps:

export default function Card({video}: Props) {
  return (
    <View style={appStyles.card}>
      <View
        style={
          video.viewedTimes > 0
            ? appStyles.cardOverlay
            : appStyles.cardNoOverlay
        }>
        <View style={appStyles.containerImage}>
          <Image source={video.thumb} style={appStyles.cardImage} />
          <View style={appStyles.containerPlayIcon}>
            <Play
              name="controller-play"
              size={35}
              color={'white'}
              style={appStyles.playIcon}
            />
          </View>
        </View>

        <View style={appStyles.underContainer}>
          <Text style={appStyles.cardText}>{__(T.cardText.title)}</Text>
          <Text style={appStyles.cardUnderText}>
            {__(T.cardText.description)}
          </Text>
        </View>
      </View>
    </View>
  );
}

And here are my translations:

export default {
  messages: {
    welcome: 'TAKE A TOUR OF THE BASILICA OF ST. FRANCIS',
    interact: 'Insert € 2.00, touch the screen',
    insert: 'You inserted :',
  },
  cardText: {
    title: "CUSTODIAN'S WELCOME SPEECH",
    description: 'bla in english',
  },
};

There are many ways of doing this, but the simplest is to build an object with your languages and translations. One level in the object is your language, and the other is a common key. Something like this:

const messages = {
  cat: {
    english: 'cat',
    italian: 'gatto',
  },
  purr: {
    english: 'purr',
    italian: 'miao',
  },
}

That way you can use it anywhere with messages[key][language] . (You could build your object so it's messages[language][key] also, up to you.)

One way to streamline this in your project would be: build a translation context that holds the user's language in memory, and returns an object with just { key: value } (ie { purr: 'miao' } . If you'd like more on that I can add it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM