Javascript React js api返回的多个组件
大家好,新年快乐 我用React JS做了一些简单的应用程序。然而,现在我正在开发一个更复杂的应用程序,我只想知道我是否朝着正确的方向前进。我没有发现任何类似的问题,所以这里是: 到目前为止,在管理部分,web编辑器可以使用3个不同的模块填充页面。这意味着我的API可以返回如下内容:Javascript React js api返回的多个组件,javascript,reactjs,Javascript,Reactjs,大家好,新年快乐 我用React JS做了一些简单的应用程序。然而,现在我正在开发一个更复杂的应用程序,我只想知道我是否朝着正确的方向前进。我没有发现任何类似的问题,所以这里是: 到目前为止,在管理部分,web编辑器可以使用3个不同的模块填充页面。这意味着我的API可以返回如下内容: { "component_name": 'x', "title": "Hello world", "body": "Nice to see you" }, { "component_name": '
{
"component_name": 'x',
"title": "Hello world",
"body": "Nice to see you"
},
{
"component_name": 'y',
"image": "http://localhost/image.png",
"title": "my fancy image"
},
{
"component_name": 'z',
"whatever": "test",
"someting": "test"
}
或者类似的事情
{
"component_name": 'x',
"title": "Hello world",
"body": "Nice to see you"
},
{
"component_name": 'x',
"title": "Hello again",
"body": "Nice to see you again"
},
{
"component_name": 'y',
"image": "http://localhost/image.png",
"title": "my fancy image"
}
因为我不知道返回什么组件,所以我编写了一个switch语句。正如我之前所说的,我没有发现任何像这样的问题,我只是想知道这是不是正确的方法?还是我在这里遗漏了什么
const { components } = this.state;
let xComponent = null;
components.map((item, index) => {
switch (item.component_name) {
case 'x':
xComponent = <xComponent title={item.title} text={item.text} />
break;
default:
}
});
return(
xComponent
)
const{components}=this.state;
设xComponent=null;
components.map((项目、索引)=>{
开关(项目组件名称){
案例“x”:
xComponent=
打破
违约:
}
});
返回(
xComponent
)
我明白你的意思。您希望基于管理内容管理器构建页面组件。我以前走过那条路,效果很好。如果您的api返回数据,则可以按照所述进行渲染。我在下面写了一个更具体的例子
class Page extends Component {
constructor(props) {
super(props);
this.state = {
pageComponents: [{
"type": 'wysiwyg',
"props": {
"title": "Hello world",
"body": "Nice to see you",
},
}, {
"type": 'video',
"props": {
"title": "Hello again",
"body": "Nice to see you again",
},
}, {
"type": 'image',
"props": {
"image": "http://localhost/image.png",
"title": "my fancy image",
},
}],
};
}
render() {
return this.state.pageComponents.map((item, i) => {
switch (item.type) {
case 'wysiwyg':
return <Wysiwyg key={i} {...item.props} />
break;
case 'video':
return <Video key={i} {...item.props} />
break;
case 'image':
return <Image key={i} {...item.props} />
break;
default:
return null;
}
});
}
};
类页扩展组件{
建造师(道具){
超级(道具);
此.state={
页面组件:[{
“类型”:“所见即所得”,
“道具”:{
“标题”:“你好,世界”,
“身体”:“很高兴见到你”,
},
}, {
“类型”:“视频”,
“道具”:{
“标题”:“再次你好”,
“身体”:“很高兴再次见到你”,
},
}, {
“类型”:“图像”,
“道具”:{
“图像”:http://localhost/image.png",
“标题”:“我的奇幻形象”,
},
}],
};
}
render(){
返回this.state.pageComponents.map((项,i)=>{
开关(项目类型){
“所见即所得”案例:
返回
打破
案例“视频”:
返回
打破
案例“图像”:
返回
打破
违约:
返回null;
}
});
}
};
你能详细说明一下你想要实现的目标吗?是有些东西不起作用还是你在寻求反馈?@azium我在寻求反馈feedback@DipenDedania我只想往正确的方向推一下。switch语句是显示组件的正确方式吗?@henrik123-我仍然不确定我是否正确理解了你的观点,但我认为在理想情况下,在ReactJS中,组件的条件呈现不需要switch语句。谢谢。这正是我想要的,我的意思,我会用这个解决方案