如何在不使用 FormattedMessage 的情况下在 ReactIntl​​ 2.0 中检索字符串

How to retrieve a string in ReactIntl 2.0 without using FormattedMessage

如有错误请指正,ReactIntl​​中的FormattedMessage returns span标签包裹的字符串。在 ReactIntl​​ 1.2 中,我们可以选择使用 this.getIntlMessage('key') 来只获取字符串部分。

这是我的问题:在 ReactIntl​​ 2.0 中是否有类似的问题?我知道可以通过在 FormattedMessage 中使用 Function-As-Child 模式作为

来获取字符串
<FormattedMessage id="placeholder">
    {(formattedValue)=>(
        <MyComponent ref="mycomponent" placeholder={formattedValue}/>
    )}
</FormattedMessage>

但是,它弄乱了我组件中的 'ref',我无法再使用 this.refs.mycomponent 访问该组件。

好的,有一个解决方法。我可以像这样在组件中添加 ReactIntl​​ 作为上下文:

contextTypes: {
    intl: React.PropTypes.object.isRequired,
},

然后当尝试检索消息的字符串并使用它时,例如在占位符中,我可以这样做。

<MyComponent ref="mycomponent" placeholder={this.context.intl.messages.placeholder}/>

您可以使用 react-intl 提供的 intl 对象轻松 return 字符串。

这就是你如何以更简单的方式在 React class 中使用 intl 对象。

note: Render Component (main component) should wrap with 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
}

通过定义 contextTypes,您可以使用作为上下文类型道具的 intl 对象。有关详细信息,请参阅反应上下文。

有更好的方法解决placeholder问题。

<FormattedMessage ...messages.placeholderIntlText>
  {
     (msg) =>  <input type="text" placeholder = {msg} />
  }
</FormattedMessage>

我使用 React render props 解决了这个问题。

我创建了一个实现它的 npm 包:http://g14n.info/react-intl-inject/

是这样的组件

import { injectIntl } from 'react-intl'

export default function reactIntlInject ({ children, ...props }) {
  if (typeof children === 'function') {
    return (
      children(props)
    )
  } else {
    return null
  }
}

你可以用它来包装组件,例如有你想要翻译的道具,例如

import React, { Component } from 'react'
// Import the package I created, available on npm with MIT license....
import InjectIntl from 'react-intl-inject'
// ...or copy the code above in a file in your project and import it, somethong like
// import InjectIntl from './path/to/my/render/prop/component'

class MyComponent extends Component {
  render () {
    return (
      <InjectIntl>
        {({ intl }) => (
          <button
            type='submit'
            value={intl.formatMessage({ id: 'enter.submit' })}
          />
        )}
      </InjectIntl>
    )
  }
}

export default injectIntl(reactIntlInject)

如果您使用的是功能组件,则可以使用 useIntl() 挂钩获取 intl 对象并从下面的代码片段中获取 string 消息。

import {IntlProvider, useIntl} from 'react-intl';

export function MyFunctionalComponent() {
    const intl = useIntl();
    return (
        <div>
            <p>{intl.formatMessage({id: "MyKey"})}</p>
        </div>
    )
}

注意:您的父组件应该包裹在 </IntlProvider> 提供者周围。

这就是我的结局。我添加了一个中央帮助功能来检索纯文本。

import { useIntl } from 'react-intl';

export const GetTranslateText = (textId) => {
  const intl = useIntl();
  const plainText = intl.formatMessage({ id: textId });

  return plainText;
};

然后它可以很好地用于检索代码或组件中的文本

import { GetTranslateText } from '/utils/IntlHelpers';
.
.
 <input type="text" placeholder={GetTranslateText('your.text.id')} /> 
.
.