通过自定义解析将html字符串渲染为React组件 [英] render html string to React component via custom parsing

查看:255
本文介绍了通过自定义解析将html字符串渲染为React组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从服务器获取了一个html字符串,如下所示:

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>

现在我想用转换html< img class =封面src =someimg.jpg> 部分转换为我自己的反应组件< LazyLoadImg className =coversrc =someimg.jpg/>

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" />.

如果没有服务器渲染或dangerouslySetInnerHTML,我该怎么做?

Without server rendering or dangerouslySetInnerHTML, how do I do that?

推荐答案

您的HTML字符串。

let responseText = '<h1>Title</h1>\n<img class="cover" src="someimg.jpg">\n<p>Introduction</p>';

按换行符拆分字符串。

let splitter = /\n/;
let broken = responseText.split(splitter);

从这里开始,删除标签以获取你真正需要的东西是一项非常简单的任务。 / p>

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);

热潮。

console.log(broken); // [ 'Title', 'someimg.jp', 'Introduction' ]

确保所有上面的逻辑最终会在组件中的正确位置。我假设您通过AJAX调用收到了原始字符串。可能会将所有内容放入回调中。

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.

这是您的组件。

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

这篇关于通过自定义解析将html字符串渲染为React组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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