React Intl,如何在消息中添加数字?

时间:2020-09-29 15:13:07

标签: reactjs react-intl

我有一个en.json文件,如下所示:

{
    "doorClosing": {
      "defaultMessage": "Doors closing",
      "description": "Elevator doors are being closed"
    },
    "floorSelected": {
      "defaultMessage": "Floor selected: {floorSelected}",
      "description": "`The floor ${lift.floorSelected} has been selected`"
    },
    "floorSelectedInvalid": {
      "defaultMessage": "Invalid floor",
      "description": "The selected floor is not valid"
    },
    "idle": {
      "defaultMessage": "",
      "description": ""
    },
    "init": {
      "defaultMessage": "Initialisation",
      "description": "The system is being initialized"
    },
    "liftMoving": {
      "defaultMessage": "Elevator moving",
      "description": "Elevator is being moved to the floor selected"
    }
}

然后在代码后面,我使用let dashboardMsg = intl.formatMessage({id:msg});,其中msg是json文件中包含的密钥之一。
关于键floorSelected,当我使用它时,${lift.floorSelected}不会被此变量中包含的数字转换。
怎么了?还有另一种方法还是必须手动执行?

3 个答案:

答案 0 :(得分:0)

您可以通过values属性传递变量:

"floorSelected": {
  "id": "selected.floor",
  "defaultMessage": "Floor selected: {floorSelected}",
}

//...

let dashboardMsg = intl.formatMessage({id:msg, values: {floorSelected: 5})

虽然不确定这是否可以用于描述。

答案 1 :(得分:0)

formatMessage将消息描述符和可选值对象作为参数。

formatMessage(messageDescriptor, values);

根据您的情况

formatMessage({ id: msg }, { floorSelected: 3 })

如果确保在所有消息描述符中添加id属性,则无需在每次渲染文本时即刻构造对象。

答案 2 :(得分:0)

您想要的被称为格式化参数。它是ICU消息语法的一部分,您可以查看here以获取更多参考。

"floorSelected": {
  "id": "floorSelected",
  "defaultMessage": "Floor selected: {floorSelected}",
  "description": "The floor {floorSelected} has been selected"
},
...

在您的代码中

const message = intl.formatMessage(messages.floorSelected, {
  floorSelected: lift.floorSelected
});

您还可以为参数指定number type,以自定义数字的格式。这是一个示例:

Number: {num} {num, number, ::currency/USD} {num, number, ::compact-long}

调用此方法时

intl.formatMessage(messages.numberExample, {
  num: 4200
})

它将被翻译为此

Number: 4200 $4,200.00 4.2 thousand

实时演示

Edit 64122522/react-intl-how-to-add-a-number-in-a-message