这似乎很简单,但是由于某些原因我无法做到。
在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标签?
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'));
请参阅文档here
render() {
return (
<div dangerouslySetInnerHTML={{ __html: '<p>This is dangerous</p>' }} />
);
}
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("");