admin管理员组

文章数量:1302900

I have a react-intl package issue. I am using an injectIntl way to use props in the ponent. Pure String is fine, but it will not work if I wrapped the HTML tag.

Pure String Success Case

const _tableNoText = intl.formatMessage(
    { id: 'footer.table_no' },
    { value: basket.table }
);
//console -> Table 1

Pure String with HTML Tag Fail Case

const _tableNoText = intl.formatMessage(
    { id: 'footer.table_no' },
    { value: <b>basket.table</b> }
);
// console -> Table [object object]

If I change the formatMessage to formatHTMLMessage, it will output the same above result, how should I fix that?

Thanks all very much.

I have a react-intl package issue. I am using an injectIntl way to use props in the ponent. Pure String is fine, but it will not work if I wrapped the HTML tag.

Pure String Success Case

const _tableNoText = intl.formatMessage(
    { id: 'footer.table_no' },
    { value: basket.table }
);
//console -> Table 1

Pure String with HTML Tag Fail Case

const _tableNoText = intl.formatMessage(
    { id: 'footer.table_no' },
    { value: <b>basket.table</b> }
);
// console -> Table [object object]

If I change the formatMessage to formatHTMLMessage, it will output the same above result, how should I fix that?

Thanks all very much.

Share edited Mar 20, 2019 at 6:12 Jordan Cheung 191 bronze badge asked Mar 20, 2019 at 3:55 tommychootommychoo 6533 gold badges12 silver badges21 bronze badges 2
  • What is your console.log statement? – Jack Bashford Commented Mar 20, 2019 at 3:59
  • @JackBashford just console.log(_tableNoText) – tommychoo Commented Mar 20, 2019 at 4:00
Add a ment  | 

1 Answer 1

Reset to default 7

When you're using { value: <b>basket.table</b> } you're in fact creating React ponent b which is an ordinary JavaScript object. This step is just hidden from you by tsx (or jsx) piler.

So if you want to render HTML you have to wrap the actual HTML string with quotes, then translate the string and then let React unwrap (or turn) the HTML string into DOM elements.

const translated = intl.formatMessage(
  { id: 'footer.table_no' },
  { value: '<strong>STRONG</strong>' }
);

return (
  <div dangerouslySetInnerHTML={{__html: translated}} />
)

If you want to interpolate basket.table just pass it as another value:

...
{
  value: '<strong>STRONG</strong>',
  table: basket.table,
}

本文标签: javascriptHow to insert HTML tag with injectIntl formatMessage using ReactIntlStack Overflow