问题
My page requires localization. I use gettext. My i18n.__
function returns translated string and replaces %s
symbols with provided arguments.
As far as I know, I can't 'dangerously set' a JSX element, however I need to insert opening and closing <Link>
tags.
I can't split the string into multiple pieces because back-end provides me such.
I am open to any ideas.
Here's my div
element:
<div
dangerouslySetInnerHTML={{ __html: i18n.__('Feel free to %scontact us%s if you have found a bug.', ['<Link to="/info">', '</Link>']) }}
/>
回答1:
The solution I found is that You use an <a>
tag instead of a <Link>
tag and fiddle with onClick
event on the whole wrapper. It goes something like this:
<div
onClick={(e) => {
this.navigate(e);
}}
>
...
<div
dangerouslySetInnerHTML={{ __html: i18n.__('Feel free to %scontact us%s if you have found a bug.', ['<a href="/info">', '</a>']) }}
/>
...
</div>
And the navigate
function checks if you have clicked on the <a>
tag and prevents the redirect by event.preventDefault()
. Then the history is "pushed":
navigate(event) {
const siteUrl = "https://www.test.com";
if (event.target.tagName === 'A') {
const href = event.target.getAttribute('href');
if (href.indexOf('mailto:') === -1) {
event.preventDefault();
this.props.history.push(href.replace(siteUrl, ''));
}
}
}
来源:https://stackoverflow.com/questions/48025373/dangerouslysetinnerhtml-and-link