dangerouslySetInnerHTML and <Link>

戏子无情 提交于 2021-02-07 10:06:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!