如何在ReactJS中用锚标记的title属性的引号标记呈现字符串

时间:2018-06-19 20:22:44

标签: javascript reactjs

考虑以下代码:

const dataObj = {
    'title': 'Who is the author of the book ‘A Brief History of Time’?',
    'link': 'https://mcqacademy.com/read-more-slug/',
    'htmlMarkup': '<p>more html markup goes here</p>',
};

return (
    <a href={dataObj.link} 
       className="read-more-link" 
       title={dataObj.title} 
       dangerouslySetInnerHTML={{__html: dataObj.htmlMarkup}}></a>
);

锚标记中的标记显示良好。问题是,当我将鼠标悬停在锚标记上时,看到的是Who is the author of the book &#8216;A Brief History of Time&#8217;?而不是Who is the author of the book 'A Brief History of Time'?

这是我在浏览器中看到的标记:

<a href="https://mcqacademy.com/read-more-slug/" class="read-more-link" title="Who is the author of the book &amp;#8216;A Brief History of Time&amp;#8217;?"><p>more html markup goes here</p></a>

标题中的标记不呈现!如何添加标题属性以正确显示?

1 个答案:

答案 0 :(得分:0)

因为title是一个字符串,而不是HTML。将标记添加为HTML时必须使用标记,如下所示:

<title>HTML content so &#8216;markup&#8217; me</title>

内部字符串属性中,您可以根据需要添加任意数量的字符而无需对其进行编码,因为浏览器知道不是要呈现的HTML,而只是一个字符串:

<element title="this is my string with <weird> characters,'single' and \"double\" quotes"/>

编辑:要使此答案更清楚,只需将您的对象更改为此:

const dataObj = {
    'title': 'Who is the author of the book \'A Brief History of Time\'?',
    'link': 'https://mcqacademy.com/read-more-slug/',
    'htmlMarkup': '<p>more html markup goes here</p>',
};