这是我的晚会:
1.应用程序请求页面内容的CMS(内容管理系统).
2. CMS返回“< div> Hi,< SpecialButton color =”red“> My Button< / SpecialButton>< / div>”
3.应用程序使用内容,使用属性中提供的数据呈现相应的组件.
我无法弄清楚如何以React方式执行第3步,任何建议都表示赞赏.
谢谢@Glenn Reyes,这是一个显示问题的Sandbox.
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'));
Here is a live demo由Vuejs制作.字符串“< div v-demo-widget>< / div>”可以视为Vuejs指令并呈现. Source Code.
解决方法:
您可能希望深入了解dangerouslySetInnerHTML
.以下是如何从React组件中的字符串呈现HTML的示例:
import React from 'react';
import { render } from 'react-dom';
const htmlString = '<h1>Hello World!