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

问题描述 投票:0回答:3

我已经知道如何通过 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>

并且显示

This is a
bold
word

问题是,如何向 i18n 模板字符串添加属性?有这个库吗?

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

// use
I18n.t("hello", { guest: "John", host: "Sam" }) 
  • 预期:
    Hello,
    John
    . I'm Sam.
  • 我得到了什么:
    Hello, <b>John</b>. I'm Sam.
react-native internationalization
3个回答
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,它在其翻译组件中支持反应内容:

<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


0
投票

这是我的手动解决方案,适用于

React-Native
I18next

1. 将此函数存储在代码中的某个位置。

export function withBoldStyle(phrase, boldPart) {
  //get index of bold part in phrase
  const startIndex = phrase.indexOf(boldPart);
  const endIndex = startIndex + boldPart.length;

  //split the long sentence into parts
  const preBold = phrase.slice(0, startIndex);
  const bold = phrase.slice(startIndex, endIndex);
  const postBold = phrase.slice(endIndex);

  //give the bold part to a bold Text component
  return [
    preBold,
    <Text style={{fontWeight: 'bold'}}>{bold}</Text>,
    postBold,
  ].filter(part => part !== '');
}

2. 像下面这样使用它:

//get your translation like the way you already do
const translation = I18n.t('hello', {guest: params.guest}); 

//in your render method, give the translation and guest name to the styling function
...
  <Text style={styles.passHint}>{withBoldStyle(translation, params.guest)}</Text>
...

注意:此函数仅限接收 1 个子字符串(粗体部分)。我会尝试改进它,以便它可以处理一系列粗体部分。

© www.soinside.com 2019 - 2024. All rights reserved.