危险地设置InnerHTML和< Link> [英] dangerouslySetInnerHTML and <Link>

查看:64
本文介绍了危险地设置InnerHTML和< Link>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面需要本地化.我使用gettext.我的 i18n .__ 函数返回翻译后的字符串,并用提供的参数替换%s 符号.

My page requires localization. I use gettext. My i18n.__ function returns translated string and replaces %s symbols with provided arguments.

据我所知,我不能危险地设置" JSX元素,但是我需要插入打开和关闭< Link> 标签.我无法将字符串分成多段,因为后端为我提供了这样的功能.

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.

我愿意接受任何想法.

这是我的 div 元素:

<div                                
    dangerouslySetInnerHTML={{ __html: i18n.__('Feel free to %scontact us%s if you have found a bug.', ['<Link to="/info">', '</Link>']) }}
/>

推荐答案

我发现的解决方案是,您使用< a> 标记而不是< Link> 标记,并在整个包装上处理 onClick 事件.它是这样的:

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>

navigate 函数检查您是否单击了< a> 标记,并通过 event.preventDefault()阻止了重定向.然后历史被推送":

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, ''));
        }
    }
}

这篇关于危险地设置InnerHTML和&lt; Link&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆