在React Native中向i18n字符串添加属性

4
我已经知道如何通过 react-native-i18n 生成i18n字符串。例如,
// en.js  source
{
  "hello": "Hello, {{name}}."
}

// use
I18n.t("hello", { name: "John" }) 

它显示 Hello, John.

我也知道如何生成带属性的字符串:

<Text>
  This is a <Text style={{fontWeight: 'bold'}}>bold<Text> word.
<Text>

它显示了这是加粗的单词

问题是,如何向i18n模板字符串添加属性?有没有任何库可以做到这一点?

// en.js  source
{
  "hello": "Hello, <b>{{guest}}</b>. I'm {{host}}."
}

// use
I18n.t("hello", { guest: "John", host: "Sam" }) 
  • 期望结果:Hello,John。我是Sam。
  • 实际结果:Hello,<b>John</b>。我是Sam。
2个回答

1
你可以这样做。
const splitTitle = (title, style) => {
    const [left, center, right] = title.split(/<b>|<\/b>/)

    return (
        <Text style={style}>
            {left}
            <Text style={{ fontFamily: 'font-name', fontWeight: 'font-weight' }}>{center}</Text>
            {right}
        </Text>
    )
}

并称之为

splitTitle(i18n.t("key"), style)

0

你可以使用react-i18next,它支持在其翻译组件中嵌入React内容:

<Trans i18nKey="userMessagesUnread" count={count}>
    Hello <strong title={t('nameTitle')}>{{name}}</strong>, you have {{count}} unread message. <Link to="/msgs">Go to messages</Link>.
</Trans>

在字典中,

"userMessagesUnread": "Hello <1>{{name}}</1>, you have {{count}} unread message. <5>Go to message</5>.",
"userMessagesUnread_plural": "Hello <1>{{name}}</1>, you have {{count}} unread messages.  <5>Go to messages</5>.",

了解更多https://react.i18next.com/latest/trans-component#using-with-react-components


1
我有没有理解错什么?这个解决方案不是让你在组件中硬编码英语翻译吗? - tomtomssi
如此混乱的组件。 - JayK
1
问题是关于React Native的。 - P Fuster
这在React Native中不起作用。 - abdou-tech

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接