reactjs - 如何在 intl.formatMessage 中使用占位符

标签 reactjs react-intl

我正在尝试使用 react-intl为我的应用添加本地化。像这样

<FormattedHTMLMessage id="marker.title" values={{
        name: (b.name !== null ? b.name : "Bench"),
        seats: Tools.showValue(b.seats),
        material: Tools.showValue(b.material),
        color: Tools.getColorNameFromInt(b.color),
        lat: b.lat,
        lng: b.lng,
    }}/>

但我需要一个字符串,所以我尝试了这个
const title = this.props.intl.formatMessage({
    id: "marker.title",
    values: {
        name: (b.name !== null ? b.name : "Bench"),
        seats: Tools.showValue(b.seats),
        material: Tools.showValue(b.material),
        color: Tools.getColorNameFromInt(b.color),
        lat: b.lat,
        lng: b.lng,
    }
});

我收到以下错误消息:
Error: The intl string context variable 'name' was not provided to the string '{name}<br/>Seats: {seats}<br/>Material: {material}<br/>Color: {color}<br/>Location: {lat} / {lng}'
en.json
{
  "marker.title": "{name}<br/>Seats: {seats}<br/>Material: {material}<br/>Color: {color}<br/>Location: {lat} / {lng}"
}

最佳答案

想通了,如果你这样做,它会起作用

this.props.intl.formatMessage({id: "marker.title"}, {
                name: (b.name !== null ? b.name : "Bench"),
                seats: Tools.showValue(b.seats, this.props.intl),
                material: Tools.showValue(b.material, this.props.intl),
                color: Tools.getColorNameFromInt(b.color, this.props.intl),
                lat: b.lat,
                lng: b.lng,
            });

让我们希望当我再次陷入这个问题时,我能再次找到这个答案。

关于reactjs - 如何在 intl.formatMessage 中使用占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50151624/

相关文章:

jquery - React 和 jQuery 事件处理程序以错误的顺序触发

react-intl - babel-plugin-react-intl : Extract strings to a single file

reactjs - react 国际 : async loading just one specific locale data in a Universal App

node.js - 使用 sass 和 babel 的 Webpack 4 生产设置

javascript - 为什么 Intl.NumberFormat 不适用于 Safari 和 Firefox 中的单位?

reactjs - Redux - reducer 中的外部库和 "React"?

reactjs - 如何处理 React-Intl 消息的多次使用?

reactjs - 将状态传递给另一个组件

reactjs - 从 React 组件加载 Django 静态文件

reactjs - React-Native 中需要 JSX