在字符串内放置html标签

问题描述 投票:1回答:3

这似乎很简单,但是由于某些原因我无法做到。

在React中,我有一个对象:

const test = {
  paragraphs: [
    'text of paragraph A text <a>link</a> text', //<a> tag will be printed just as a string
    'text of paragraph B text text',
  ]
}

我正在映射段落,以便呈现一些段落,就像这样。

test.paragraphs.map(item => <p>item</p>)

所有作品都很好。但是,如果我想在第一段中放入链接标记,该怎么办。如何在页面的第一个字符串内嵌入html标签?

javascript reactjs
3个回答
0
投票
class App extends React.Component { constructor() { super(); this.state = { description: '<a href={to} target="_blank" {...rest}>{children}</a>' } } render() { return ( <div dangerouslySetInnerHTML={{ __html: this.state.description }} /> ); } } ReactDOM.render(<App />, document.getElementById('root'));

0
投票
因此,React允许您使用危险地设置InnerHTML道具将HTML代码注入HTML组件中。风险自负:)

请参阅文档here

render() { return ( <div dangerouslySetInnerHTML={{ __html: '<p>This is dangerous</p>' }} /> ); }


-1
投票

const test = { paragraphs: [ 'text of paragraph A text http://google.com', 'text of paragraph B text text', 'text of paragraph http://www.yahoo.com B text text', 'text http://google.com of paragraph http://www.yahoo.com B text text', ] }; const res = test.paragraphs.map(p=>{ return `<p>${p.replace(/http(s)?\:\/\/(www.)?[a-zA-Z]+\.[a-z]+/g, (link)=>`<a href="${link}">${link}</a>`)}</p>`; }); document.body.innerHTML = res.join("");
© www.soinside.com 2019 - 2024. All rights reserved.