首页 > 解决方案 > 如何使用 FormattedMessage 将对象转换为字符串以使用 REACTJs 在 d3.js 图表中呈现标签?

问题描述

我正在尝试使用翻译数据的 react-intl 制作一个支持多语言的应用程序。在执行此操作时,我面临一个问题,当我尝试翻译时它会将我返回为 [OBJECT OBJECT] 但我期待一个字符串。

我使用“react-intl”:“2.7.2”进行翻译,“react-c3js”:“^0.1.20”,用于渲染c3 JS图表

条形图代码。在此我希望将标签翻译成不同的语言

     <BarChartWithLine
                          data={this.state.topMerchants}
                          xAxisLable={<InjectIntl/>}
                          yAxisLable="TRANSACTION COUNT"
                          y2AxisLable="SUCCESS RATE"
                          barColor="#6BD0F6"
                          successRateData={
                            this.state.topMerchantsSuccessRate
                          }

在 injectIntl​​ 文件中

  const LocalesMenu = ({ intl }) => {
     const placeholder = intl.formatMessage({id: 'transaction.merchantID'});
return (<div>{placeholder}</div>);     
}

我得到输出为 [OBJECT OBJECT]

在此处输入图像描述

标签: javascriptreactjsd3.jsinternationalizationreact-intl

解决方案


您可以将函数用作文档中的子函数 https://github.com/formatjs/react-intl/blob/master/docs/Components.md#formattedmessage

<FormattedMessage id="transaction.merchantID">
    {(text) => (
        <BarChartWithLine
           data={this.state.topMerchants}
           xAxisLable={text}
           yAxisLable="TRANSACTION COUNT"
           y2AxisLable="SUCCESS RATE"
           barColor="#6BD0F6"
           successRateData={
             this.state.topMerchantsSuccessRate
           }
         />
    )}
</FormattedMessage>

如果你也想反xAxisLableyAxisLable。就这样包起来。但是现在的代码很难阅读

<FormattedMessage id="transaction.merchantID">
   {(text) => (
      <FormattedMessage id="transaction.xAxisLable">
         {(text2) => (
            <BarChartWithLine
               data={this.state.topMerchants}
               xAxisLable={text}
               yAxisLable="TRANSACTION COUNT"
               y2AxisLable="SUCCESS RATE"
               barColor="#6BD0F6"
               successRateData={
                 this.state.topMerchantsSuccessRate
               }
            />
          )}
      </FormattedMessage>
   )}
    </FormattedMessage>

我认为这段代码更好,更具可读性,但有点棘手。transaction.merchantID是这样的文本“xAxisLable;yAxisLable;y2AxisLable”

<FormattedMessage id="transaction.merchantID">
   {(text) => {
      const [xAxisLable, yAxisLable, y2AxisLable] = text.split(';')
      return (
      <BarChartWithLine
         data={this.state.topMerchants}
         xAxisLable={xAxisLable}
         yAxisLable={yAxisLable}
         y2AxisLable={y2AxisLable}
         barColor="#6BD0F6"
         successRateData={
           this.state.topMerchantsSuccessRate
         }
      />
        )
    }}
 </FormattedMessage>

推荐阅读