How to retrieve a string in ReactIntl 2.0 without using FormattedMessage

前端 未结 4 1976
南笙
南笙 2021-01-02 03:29

Please correct me if I am wrong, FormattedMessage in ReactIntl returns a string wrapped by span tags. In ReactIntl 1.2, we have the option to use this.getIntlMessage(\

4条回答
  •  醉梦人生
    2021-01-02 04:02

    I solved this problem using React render props.

    I created an npm package that implements it: http://g14n.info/react-intl-inject/

    It is a component like this

    import { injectIntl } from 'react-intl'
    
    export default function reactIntlInject ({ children, ...props }) {
      if (typeof children === 'function') {
        return (
          children(props)
        )
      } else {
        return null
      }
    }
    

    And you can use it to wrap the components that for example has props you want to translate, for example

    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 (
          
            {({ intl }) => (
              

提交回复
热议问题