javascript - 如何使用 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]
解决方案
您可以将函数用作文档中的子函数 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>
如果你也想反xAxisLable
式yAxisLable
。就这样包起来。但是现在的代码很难阅读
<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>
推荐阅读
- xamarin.forms - 如何使用 Xamarin.Forms 和 MvvmCross 设置我的 UWP 项目
- c# - C# for 循环,通过用户指定的数字给出 i/(i+1) 的总和
- bitbucket - Bitbucket Hooks 与 Webhooks
- php - 如何删除两个文本字段之间的空格
- php - 检索 exercise_day 等于当天的记录
- json - 解组到自定义接口
- python - 从权限类访问 hyperlinkedRelatedField 对象
- django - jqgrid 在 Django 模板中的使用:“item-jqgrid-entity1”的反向
- jenkins - 从工件中选择工件以在 Jenkins 中部署管道作业
- elasticsearch - 新记录未出现在弹性搜索结果中