如何在 react-native 中使用 i18n-js 将组件渲染为参数?

IT技术 javascript reactjs react-native localization i18n-js
2021-05-18 06:54:26

我使用i18n-js进行语言环境和翻译。我正在尝试使用插值渲染本机组件。

以下是参考代码,

// Translate function (exposed using custom hooks)
const translate = useCallback((key, config) => i18n.t(key, config), []);
// locale key with variables to be interpolated
"tnc_text": "Accept {{topUpTnC}} and {{dealsTnC}} to proceed"
// Code which uses translate
<Text>
  {translate(
    'tnc_text', {
      topUpTnC: <Text
        style={{color: 'blue'}}
        onPress={() => Linking.openURL('https://google.com')}>
        Top-Up Terms and Conditions*
      </Text>,
      dealsTnC: <Text
        style={{color: 'blue'}}
        onPress={() => Linking.openURL('https://example.com')}>
        Deals Terms and Conditions
      </Text>,
  })}
</Text>

我期待这样的事情:

接受充值条款和条件*以及交易条款和条件以继续

但相反,我得到了这个:

接受 [object Object] 和 [object Object] 以继续

在文档中找不到任何内容。有没有办法用 i18n-js 中的组件替换变量?

1个回答

我遇到了同样的问题,但还没有找到答案...

也许跨组件可以帮助:

https://react.i18next.com/latest/trans-component

编辑:这可能是一个很好的解释 React-i18n Trans Component with translations that contains HTML tags not working

第二次编辑: 我可以使用以下代码解决问题:

// render
<Trans i18nKey="yourTranslationKey" components={{ link: <Text onPress={() => console.log('do something')}}} /> }} />

// translationFile
{...
 "yourTranslationKey": "Please <link>Click me</link>",
...}

github上找到它:)

是关于它的官方文档。