C.L*_*Lee 10 reactjs react-intl
如果我错了请纠正我,ReactIntl中的FormattedMessage返回一个由span标签包装的字符串.在ReactIntl 1.2中,我们可以选择this.getIntlMessage('key')仅使用字符串部分.
这是我的问题:在ReactIntl 2.0中是否有相同的功能?我知道可以通过使用FormattedMessage中的Function-As-Child模式获得字符串
<FormattedMessage id="placeholder">
{(formattedValue)=>(
<MyComponent ref="mycomponent" placeholder={formattedValue}/>
)}
</FormattedMessage>
Run Code Online (Sandbox Code Playgroud)
但是,它会混淆我的组件中的'ref',我无法再使用该组件this.refs.mycomponent了.
您可以使用react-intl提供的intl对象轻松返回字符串.
这就是你如何以更简单的方式在反应类中使用intl对象.
注意:渲染组件(主要组件)应该使用IntlProvider进行换行
class MySubComponent extends React.Component{
{/*....*/}
render(){
return(
<div>
<input type="text" placeholder = {this.context.intl.formatMessage({id:"your_id", defaultMessage: "your default message"})}
</div>
)
}
}
MySubComponent.contextTypes ={
intl:React.PropTypes.object.isRequired
}
Run Code Online (Sandbox Code Playgroud)
通过定义contextTypes,它将使您能够使用作为上下文类型prop的intl对象.有关详细信息,请参阅react context.
小智 8
有一个更好的解决placeholder问题.
<FormattedMessage ...messages.placeholderIntlText>
{
(msg) => <input type="text" placeholder = {msg} />
}
</FormattedMessage>
Run Code Online (Sandbox Code Playgroud)
好的,有一个解决方法.我可以在组件中添加ReactIntl作为上下文,如下所示:
contextTypes: {
intl: React.PropTypes.object.isRequired,
},
Run Code Online (Sandbox Code Playgroud)
然后,当试图检索消息的字符串并使用它时,例如在占位符中,我可以这样做.
<MyComponent ref="mycomponent" placeholder={this.context.intl.messages.placeholder}/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6878 次 |
| 最近记录: |