通过自定义解析将html字符串渲染为React组件

时间:2016-04-27 19:17:21

标签: javascript reactjs react-dom

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

<img class="cover" src="someimg.jpg">

现在我想转换html,<LazyLoadImg className="cover" src="someimg.jpg" />部分转换为我自己的React Component class MyWizardView(SessionWizardView): unique_id == "" def get(self, request, *args, **kwargs): """ This method handles GET requests. If a GET request reaches this point, the wizard assumes that the user just starts at the first step or wants to restart the process. The data of the wizard will be resetted before rendering the first step """ self.storage.reset() # reset the current step to the first step. self.storage.current_step = self.steps.first unique_id = # Insert ID generator here # return self.render(self.get_form())

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

1 个答案:

答案 0 :(得分:0)

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

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

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调用收到了原始字符串。可能把所有这些东西放在回调中。

这是你的组件。

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