如何使用intl.formatMessage占位符

时间:2018-05-03 09:32:17

标签: 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}"
}

1 个答案:

答案 0 :(得分:1)

如果你这样做就会搞清楚它会起作用

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,
            });

我希望当我再次坚持这件事时,我会再次找到这个答案。