2015-12-14 56 views
0

我有一個簡單的<Trans/>反應組件,它允許翻譯具有一些屬性的鍵(我使用sprintf)。例如:反應組件裏面內插的反應組件

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

呈現:

的Hello World

問題努力使其中的一些特性的動態時,說的不是 「世界」 我想有

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

現在,什麼反應是首先輸出以下內容:

你好[目標對象]

之前下降渲染路徑和正確渲染

你好藍色星球

這導致呈現出一個小的Flickr [對象對象]而不是渲染的元素。我試圖使用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> 
    ) 
    } 
} 
+0

'%(color)s planet'什麼是動態的?看起來與 Hello%(planet)s'相同,但是具有不同的道具名稱。 – theodor

回答

0

您需要確保顏色原型上的#toString()方法返回您想要的。

+0

對不起,我應該在第一時間把全班同學包括在內,但現在就加入。沒有toString方法 - 它只是一個sprintf函數,用props傳遞的數據替換props.children中的鍵。 –