如何解析HTML到React组件? [英] How to parse html to React component?

查看:386
本文介绍了如何解析HTML到React组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的senario:

1.应用程序请求CMS(内容管理系统)用于页面内容。

2. CMS返回< div> ;< SpecialButton color =red> My Button< / SpecialButton>< / div>

3.应用程序消耗内容,数据在属性中提供。

This is my senario :
1. Application request CMS(Content management system) for page contents.
2. CMS return "<div>Hi,<SpecialButton color="red">My Button</SpecialButton></div>"
3. Application consume the content, render corresponding component with data provided in attribute.

我无法弄清楚如何在React方法中执行第3步,任何建议都会被赞赏。

I can't figure out how to do step 3 in React way, any advice is appreciated.

感谢@Glenn Reyes,这里是沙盒以显示问题。

Thanks @Glenn Reyes, here's a Sandbox to show the problem.

import React from 'react';
import { render } from 'react-dom';

const SpecialButton = ({ children, color }) => (
  <button style={{color}}>{children}</button>
);

const htmlFromCMS = `
<div>Hi, 
  <SpecialButton color="red">My Button</SpecialButton>
</div>`;

const App = () => (
  <div dangerouslySetInnerHTML={{__html: htmlFromCMS}}>
  </div>
);

// expect to be same as
// const App = () => (
//   <div>Hi, 
//     <SpecialButton color="red">My Button</SpecialButton>
//   </div>
// );

render(<App />, document.getElementById('root'));

这是Vuejs制作的现场演示。 String < div v-demo-widget>< / div>可以视为Vuejs指令并呈现。 源代码

Here is a live demo made by Vuejs. String "<div v-demo-widget></div>" could be treat as Vuejs directive and rendered. Source Code.

推荐答案

您可能想深入了解 dangerouslySetInnerHTML 。下面是一个示例,说明如何从React组件中的字符串呈现HTML:

You probably want to look deeper into dangerouslySetInnerHTML. Here is an example how to render HTML from a string in a React component:

这篇关于如何解析HTML到React组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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