React-Intl:带数组的 I18n

我目前正在开发一个从两个 json 文件(de.json 和 en.json)中读取数据的网站。现在还有一个页面,我需要根据选择的语言从英语数组或德语数组中读取数据(每个数组当前都是一个简单的 js 文件,其中只有数组,它只是被导入我需要读取其数据的文件)。它现在的工作方式是我检查语言环境是否为英语,然后使用该数组,但是该解决方案并不干净。


const ResourcesMedia = [

    {

        title: 'sometitle',

        description: 'somedescription',

        href: 'somelink'

    },

    {

        title: 'sometitle',

        description: 'somedescription',

        href: 'somelink'

    }

  ]


export default ResourcesMedia;

还有另一个类似的数组仅适用于德语版本。现在根据选择的语言,我正在映射数组并创建组件。但是,目前我正在检查语言环境是这样的:


const mediaArray = locale === 'en' ? ResourcesMediaEn : ResourcesMedia

这不是最好的方法,而是我想将数组存储在 en.json 和 de.json 文件(或两个新文件)中,让 IntlProvider 决定它应该使用哪个。有没有用 React-Intl 做到这一点的好方法,还是我需要以其他方式实现它?


HUX布斯
浏览 154回答 1
1回答

慕姐4208626

您可以创建一个数组,其中数组中的值是键而不是实际字符串,并且在渲染它们时,您可以实际翻译这些const ResourcesMedia = [&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; title: 'sometitleKey',&nbsp; &nbsp; &nbsp; &nbsp; description: 'somedescriptionKey',&nbsp; &nbsp; &nbsp; &nbsp; href: 'somelink'&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; title: 'sometitleKey1',&nbsp; &nbsp; &nbsp; &nbsp; description: 'somedescriptionKey',&nbsp; &nbsp; &nbsp; &nbsp; href: 'somelink'&nbsp; &nbsp; }&nbsp; ]render() {&nbsp; &nbsp;const {intl: {formatMessage: t}} = this.props;&nbsp; &nbsp;return ResourcesMedia.map(item => (&nbsp; &nbsp; &nbsp; &nbsp;<div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div>{t(item.title)</div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div>{t(item.description)</div>&nbsp; &nbsp; &nbsp; &nbsp;<div>&nbsp; &nbsp;))}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript