【发布时间】:2017-11-22 10:17:50
【问题描述】:
这是我的情景:
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 制作。 String "<div v-demo-widget></div>" 可以被视为 Vuejs 指令并被渲染。 Source Code.
【问题讨论】:
-
Andy 没有明确的答案,但可能能够为您指明一个方向,具体取决于您获取 CMS 数据的方式。您是否尝试过使用更高阶的组件来呈现从请求返回的组件?我认为一个组件然后呈现您请求的组件可能是要走的路。
-
@BrettEast,更高阶的组件可以执行请求,但我的问题是在从 CMS 获取
<h4>Hello</h4><reactcomponenct attr1="foo"></mycomponenct>之类的字符串后,如何让反应知道<reactcomponenct attr1="foo"></mycomponenct>的部分是组件,需要执行组件的代码。 -
是的,这很棘手,您的传入数据是否有可能遵循反应命名模式,反应组件使用大写字母,html 元素使用小写字母?也许正则表达式可以解决问题?
-
是的,我认为遵循 react 命名模式是可以的,但看起来我需要编写一个编译器来执行类似 angular 指令的操作...
标签: javascript html reactjs compilation content-management-system