首页 > 解决方案 > 如何从对象映射中渲染 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();
        </>
    );
};

标签: javascriptreactjs

解决方案


你的数组声明是错误的。您应该使用包含对象的对象或数组。试试这个块。

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;

推荐阅读