Reactjs 内插反应组件内的反应组件
我有一个简单的Reactjs 内插反应组件内的反应组件,reactjs,Reactjs,我有一个简单的React组件,它允许翻译带有一些属性的密钥(我使用sprintf)。例如: <Trans planet="World">Hello %(planet)s</Trans> Hello%(行星)s 呈现: 你好,世界 问题是,当尝试动态呈现其中一些属性时,比如说,而不是我想要的“世界” <Trans color="blue">%(color)s planet</Trans> %(彩色)s行星 现在,react首先输出以下内容:
React组件,它允许翻译带有一些属性的密钥(我使用sprintf)。例如:
<Trans planet="World">Hello %(planet)s</Trans>
Hello%(行星)s
呈现:
你好,世界
问题是,当尝试动态呈现其中一些属性时,比如说,而不是我想要的“世界”
<Trans color="blue">%(color)s planet</Trans>
%(彩色)s行星
现在,react首先输出以下内容:
你好[对象]
在沿着渲染路径继续并正确渲染之前
你好,蓝色星球
这会导致显示[object object]而不是渲染元素的小flickr。我曾尝试使用renderToString,但它会迫使我使用一些危险的HTML,这些HTML不适用于其他翻译约束
有什么想法吗
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>
)
}
}
import React,{PropTypes,Component}来自“React”
从“sprintf js”导入{sprintf}
导出默认类Trans扩展组件{
翻译(键,args){
如果(this.props.context&&this.props.context[key])key=this.props.context[key]
else console.error(“%s不在已翻译的键中”,键“-context was”,this.props.context)
if(键的类型==='object'&&key.singular){
如果(此.props.isPlural)
返回sprintf(key.复数,args)
其他的
返回sprintf(key.singular,args)
}
返回sprintf(键,参数)
}
render(){
返回(
{this.translate(this.props.children,this.props)}
)
}
}
您需要确保颜色原型上的#toString()
方法返回您想要的结果。%(颜色)s planet
动态是什么意思?看起来与Hello%(planet)s
相同,但道具名称不同。很抱歉,我应该从一开始就把整个班级都包括在里面,但现在才添加。没有toString方法——它只是一个sprintf函数,用作为props传递的数据替换props.children中的键。