如何使用react-native-i18n翻译数组?

时间:2017-05-16 17:08:47

标签: javascript react-native

我的翻译是这样的:

en.json

{
   "Welcome": "Welcome to react native",
   "days": ["Sun","Mon","Tue","Wed","Thur","Fri","Sat"]
}

和我的页面是这样的:

import React, { PropTypes } from 'react';
import { View, Image } from 'react-native';
import i18n from 'react-native-i18n';
import ReactNativeCalendar from 'react-native-calendar';
import translations from '../../translations';
import styles from './styles';

const dayHeadings = i18n.t('days');

[...]

const Calendar = (props) => {
  console.log(dayHeadings);
  return (
    <View>
      <ReactNativeCalendar
        customStyle={styles}
        nextButtonText={nextButton}
        prevButtonText={prevButton}
        dayHeadings={dayHeadings}
        monthNames={monthNames}
        onDateSelect={props.onDateSelect}
        eventDates={props.eventDates}
        showEventIndicators
        showControls
        events={props.events}
        calendarFormat={props.calendarFormat}
      />
      <Legend items={legendItems} />
    </View>
  );
};

dayHeadings应该是一个已翻译的字符串数组,但我得到了

  

缺少&#34; en.days&#34;翻译

从控制台

。奇怪的是,如果我保存翻译并触发热重载,翻译工作就可以了like here。翻译也出现在文件screenshot

1 个答案:

答案 0 :(得分:4)

最好的方法是声明:

{
   "Welcome": "Welcome to React Native",
   "days": {
    "sun": "Sun",
    "mon": "Mon",
    "tue": "Tue",
    "wed": "Wed",
    "thu": "Thur",
    "fri": "Fri",
    "sat": "Sat"
  }
}

然后参考:

I18n.t(['days', 'mon']);

假设您要显示所有日期(例如在日历中),请转到:

const dayKeys = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
...
render() {
  return (
    <View>
    {dayKeys.map((key) => <Text>{I18n.t(['days', key])}</Text>)}
    </View>
  )
}