13

間違っている場合は修正してください。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>

ただし、コンポーネントの「参照」が台無しになり、それ以上使用してコンポーネントにアクセスできませんthis.refs.mycomponent

4

5 に答える 5

0

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)
于 2019-03-31T18:56:41.807 に答える