内插React组件中的React组件

时间:2015-12-14 19:48:21

标签: reactjs

我有一个简单的<Trans/> React组件,它允许使用某些属性转换键(我使用sprintf)。例如:

<Trans planet="World">Hello %(planet)s</Trans>

呈现:

  

Hello World

问题在于尝试动态渲染其中一些属性,而不是&#34; World&#34;我想要

<Trans color="blue">%(color)s planet</Trans>

现在,做出反应的是首先输出以下内容:

  

Hello [object Object]

在进入渲染路径并正确渲染之前

  

Hello blue planet

这导致显示[object Object]而不是渲染元素的一点点闪烁。我曾尝试使用renderToString,但这会迫使我使用一些不能与其他翻译约束一起使用的危险的SetInnerHTML。

有什么想法吗?

import React, {PropTypes, Component} from 'react'
import {sprintf} from 'sprintf-js'

export default class Trans extends Component {
  translate(key, args){
    if(this.props.context && this.props.context[key]) key = this.props.context[key]
    else console.error('%s is not in translated keys', key, ' - context was ', this.props.context)
    if(typeof key === 'object' && key.singular){
      if(this.props.isPlural)
        return sprintf(key.plural, args)
      else
        return sprintf(key.singular, args)
    }
    return sprintf(key, args)
  }

  render() {
    return (
      <span>
        {this.translate(this.props.children, this.props)}
      </span>
    )
  }
}

1 个答案:

答案 0 :(得分:0)

您需要确保颜色原型上的#toString()方法返回您想要的内容。

相关问题