- 在项目中安装i18next和i18next-icu插件:
npm install i18next i18next-icu
- 导入所需的依赖项和配置i18next:
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import ICU from "i18next-icu";
i18n
.use(ICU)
.use(initReactI18next)
.init({
resources: {
en: {
translation: {
dateMessage: "Today is {date, date, full}"
}
}
},
lng: "en",
interpolation: {
escapeValue: false // 不需要转义HTML代码
}
});
- 在消息文件中使用日期格式:
{
"dateMessage": "Today is {date, date, full}"
}
- 在组件中使用i18next和使用日期格式:
import React from "react";
import { useTranslation } from "react-i18next";
function DateMessage() {
const { t } = useTranslation();
const date = new Date();
const formattedDate = new Intl.DateTimeFormat("en", {
year: "numeric",
month: "long",
day: "numeric"
}).format(date);
return <div>{t("dateMessage", { date })}</div>;
}