问题
I have a html string fetched from server which looks like this:
<h1>Title</h1>\n<img class="cover" src="someimg.jpg">\n<p>Introduction</p>
Now I want to transform the html with <img class="cover" src="someimg.jpg">
part converted to my own React Component <LazyLoadImg className="cover" src="someimg.jpg" />
.
Without server rendering or dangerouslySetInnerHTML, how do I do that?
回答1:
Your HTML string.
let responseText = '<h1>Title</h1>\n<img class="cover" src="someimg.jpg">\n<p>Introduction</p>';
Splitting the string by line breaks.
let splitter = /\n/;
let broken = responseText.split(splitter);
From here, it's a pretty simple task to strip out tags to get the stuff you really need.
broken[0] = broken[0].slice(4, broken[0].length - 5);
broken[1] = broken[1].slice(24, broken[1].length - 3);
broken[2] = broken[2].slice(3, broken[2].length - 4);
Boom.
console.log(broken); // [ 'Title', 'someimg.jp', 'Introduction' ]
Make sure all the above logic ends up in the right place within your component. I'm assuming that you received the original string via AJAX call. Probably put all that stuff in the callback.
Here's your component.
class ProfileSection extends React.Component {
constructor(props) {
super(props);
}
state = {
}
render () {
return (
<div>
<h1>{broken[0]}</h1>
<LazyLoadImg className="cover" src={broken[1]} />
<p>
{broken[2]}
</p>
</div>
);
}
}
来源:https://stackoverflow.com/questions/36898978/render-html-string-to-react-component-via-custom-parsing