javascript - 如何从对象映射中渲染 React.js 中的元素
问题描述
我有一个关于从对象映射渲染组件的问题。我有这样的结构:
const tabs = [
'tab1': {
name: 'Tab 1',
renderComponent: () => <Tab1Component />
},
'tab2': {
name: 'Tab 2',
renderComponent: () => <Tab2Component />
}
];
我想访问 renderComponent 属性并渲染子组件。尝试使用函数调用 React.createElement() 不起作用。
const MyComponent = ({tabs}) => {
const activeTab = 'tab1';
return (
<>
// How to render it?
// function invocation?
// createElement??
tabs[activeTab].renderComponent();
</>
);
};
解决方案
你的数组声明是错误的。您应该使用包含对象的对象或数组。试试这个块。
const tabs = {
tab1: {
name: "Tab 1",
renderComponent: () => <Tab1Component />
},
tab2: {
name: "Tab 2",
renderComponent: () => <Tab2Component />
}
};
也用like包围你的js代码{}
;
const MyComponent= () => {
const activeTab = "tab1";
return <>{tabs[activeTab].renderComponent()}</>;
};
export default MyComponent;
推荐阅读
- r - 在 Shiny 中调整滑块输入功能
- many-to-many - 具有多对多关系的 DDD 聚合设计示例
- textview - 获取选定的 TextView 文本
- javascript - geolocation.getCurrentPosition 在边缘不起作用
- mysql - 如何诊断极慢的 AWS RDS MySQL 性能?
- mysql - SQL (mysql) 查询世界数据库
- java - 在异步任务Android中膨胀弹出窗口
- javascript - 在可调整大小的 div 中隐藏“调整大小”句柄?
- python - 缓冲区 dtype 不能是 numba 中的缓冲区
- android - Toast 消息在 Recycler 视图中不起作用