[英]Reactjs Render component dynamically based on a JSON config
我有一個以下配置作為JSON
var componentConfig = {
content: { type: "ContentContent", data: "content"},
new_content: { type: "ContentFormContent", data: "content"}
}
在react rendercomponent中,是否可以動態傳遞組件名稱以進行反應渲染。
例如,在這個rendercomponent而不是直接放置ContentFormContent是可以從json配置傳遞數據,我可以循環或東西。
React.renderComponent(<ContentFormContent data={[componentConfig.new_content.data]} />, body);
所以我將在json配置中有一個頁面列表,並根據特定導航的選擇,我將根據json文件中的“類型”渲染組件
JSX
<ContentFormContent data={[componentConfig.new_content.data]} />
簡單地編譯成
ContentFormContent({data: [componentConfig.new_content.data]})
所以你可以隨心所欲地打電話。 在這種情況下,最方便的是列出所有可能的組件並執行類似的操作
var allComponents = {
ContentContent: ContentContent,
ContentFormContent: ContentFormContent
};
// (later...)
React.renderComponent(allComponents[component.type]({data: component.data}), body);
if component
是示例數組中的元素。
不推薦使用React.renderComponent(),以使用React.render() https://facebook.github.io/react/blog/2014/10/28/react-v0.12.html#deprecations
你可以這樣做:
var loadReactModule = function ($root, type, data) {
var ContentContent= React.createClass({
render: function () {
return (
<input type="text" placeholder="My Module-Input"/>
);
}
});
var ContentFormContent= React.createClass({
render: function () {
return (
<form></form>
);
}
});
var allComponents = {
ContentContent: ContentContent,
ContentFormContent: ContentFormContent
};
if (type in allComponents) {
$root.each(function (index, rootElement) {
React.render(React.createElement(allComponents[type]), {data:data}, rootElement);
});
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.