首页 > 解决方案 > 为什么我的嵌套复数 ICU 消息在 react-intl FormattedMessage 中不起作用?

问题描述

我正在使用 react-intl 及其<FormattedMessage />标签。

我想要一个结构化的消息,它将根据提供的值选择正确的复数变体,以允许翻译人员使用他们的语言规则,即,如果他们对“一”、“二”、“多”有不同的变体,项目等。我不想通过switch仅对“零”、“一”和“其他”使用英语规则的语句将其硬编码在应用程序业务逻辑中。

<FormattedMessage id="myMessage" values={{applesCount: 4, orangesCount: 0, pearsCount: 1}} /> 应该I have some apples and some pears从以下来源产生。

由于某些原因,它返回I have some apples, some pears, and some oranges

{applesCount, plural, 
    zero {{pearsCount, plural, 
        zero {{orangesCount, plural, 
            zero {I have no fruit}
            other {I have some oranges}
        }}
        other {{orangesCount, plural, 
            zero {I have some pears}
            other {I have some pears and some oranges}
        }}
    }}
    other {{pearsCount, plural, 
        zero {{orangesCount, plural, 
            zero {I have some apples}
            other {I have some apples and some oranges}
        }}
        other {{orangesCount, plural, 
            zero {I have some apples and some pears}
            other {I have some apples, some pears, and some oranges}
        }}
    }}
}

我通过https://format-message.github.io/icu-message-format-for-translators/editor.html对其进行了测试

另外,我有这个代码框,您可以在其中修改它: https ://codesandbox.io/s/react-intl-formattedmessage-using-plural-x8ki5

作为参考,我检查了http://userguide.icu-project.org/formatparse/messageshttps://formatjs.io/guides/message-syntax/并希望我的消息结构受支持。

你能帮我检测出什么问题或者我应该如何改变它以使其正常工作?

标签: reactjslocalizationtranslationicureact-intl

解决方案


问题是:

英语作为一门语言没有专门针对零项目的语法

它主要是单数或复数(在一些罕见的剩余情况下为dual)。

您使用的语法专门针对那些语法专门针对零个项目的语言。(例如阿拉伯语和拉脱维亚语)

在这里阅读:https ://formatjs.io/guides/message-syntax/#plural-format 。此外,维基百科
上的这篇文章解释了相同的

因此,该方法不适用于英语。相反,您需要使用=0(=value 语法) 将数量匹配为零以使解决方案起作用。

{applesCount, plural, 
    =0 {{pearsCount, plural, 
        =0 {{orangesCount, plural, 
            =0 {I have no fruit}
            other {I have some oranges}
        }}
        other {{orangesCount, plural, 
            =0 {I have some pears}
            other {I have some pears and some oranges}
        }}
    }}
    other {{pearsCount, plural, 
        =0 {{orangesCount, plural, 
            =0 {I have some apples}
            other {I have some apples and some oranges}
        }}
        other {{orangesCount, plural, 
            =0 {I have some apples and some pears}
            other {I have some apples, some pears, and some oranges}
        }}
    }}
}

同样,对于 1 个数字,one不适用于英语。您必须使用=value语法 ( =1)。在沙盒
上试过这个并且工作正常。

希望能帮助到你。如有任何疑问,请回复。


推荐阅读