简体   繁体   中英

react Intl - how to get value from formattedMessage

I have a component that takes a number. <ClickableNumber num={num} />

I'm getting this number from my language pack with a FormattedMessage
<ClickableNumber num={<FormattedMessage id="native_number" />} />

when I console log num inside ClickableNumber it is an object.

How do I get the string or number version of the value from <FormattedMessage id="native_number" /> ?

I can get the value if I used intl.formatMessage({ id: 'native_number' }) but I'm trying to reuse the ClickableNumber and do not want to wrap each component that uses this component in injectIntl

I've never used react-intl so I don't know if its gonna work or not but it should work in concept.

What you can do is that create a utility function that will return the desired result. For this situation intl.formatMessage({ id: 'native_number' }) and the formatted Component.

const getNativeNumber = () => {
   // I don't know how but you can get the number here
   // something like
   const nativeNumber = intl.formatMessage({ id: 'native_number' });
   return {
     component: <FormattedMessage id="native_number" />,
     nativeNumber: nativeNumber
   }
}

<ClickableNumber num={getNativeNumber()} />

console.log(this.props.num.nativeNumber)  // This will have the native number in your ClickableNumber component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM