首页 > 解决方案 > 如何制作可重用的材质 UI 选项卡组件 - 反应

问题描述

我正在处理一个反应项目,我使用MUI Tab 组件将一些页面划分为选项卡,因此我可以在一个页面中有多个组件并相应地渲染每个组件,因此创建了 Tabs 组件但是我只能看到一个第一个索引选项卡,谢谢

可重复使用的 tab mui 组件:-

export default function useTabs(props) {
  const { children, value, index, label, ...other } = props;

  const [selectedValue, setSelectedValue] = React.useState(0);

  const handleChange = (event, newValue) => {
    setSelectedValue(newValue);
  };

  return (
    <Box sx={{ width: "100%" }}>
      <Box sx={{ borderBottom: 1, borderColor: "divider" }}>
        <Tabs
          value={selectedValue}
          onChange={handleChange}
          className={classes.tab}
          textColor="primary"
          indicatorColor="primary"
        >
          <Tab label={label} {...a11yProps(0)} className={classes.tabText} />
          {/* <Tab className={classes.tabText} label={label} {...a11yProps(1)} /> */}
        </Tabs>
      </Box>
      <TabPanel value={selectedValue} index={index}>
        {children} // rendering tab children here but getting only the first component
      </TabPanel>
    </Box>
  );
}

这是我使用它的方式:-

//import the reusable component
import Tab from "../common/Tabs";
export default function JobsRecruitments() {
return (
<>
<Tab label="tab name" index={0}> 
<MyComponent />
</Tab>
</>
)
}

标签: reactjsmaterial-ui

解决方案


children如果您想要可重复使用的标签,我认为使用它不是一个好主意。那是因为你的标签必须是一致的:如果你有 3 个子节点,你也应该有 3 个标签标签。如果您正在使用children,您很容易忘记这一点。

但是,如果您想制作一个可重用的选项卡组件,我建议将包含选项卡标签和 Component 的对象数组作为属性传递给您的自定义Tab组件。这是我的意思的一个例子:

export default function BasicTabs({ tabs }) {
  const [value, setValue] = React.useState(0);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  return (
    <Box sx={{ width: "100%" }}>
      <Box sx={{ borderBottom: 1, borderColor: "divider" }}>
        <Tabs
          value={value}
          onChange={handleChange}
          aria-label="basic tabs example"
        >
          {tabs.map(({ label }, i) => (
            <Tab label={label} key={i} />
          ))}
        </Tabs>
      </Box>
      {tabs.map(({ Component }, i) => (
        <TabPanel value={value} index={i} key={i}>
          {Component}
        </TabPanel>
      ))}
    </Box>
  );
}

然后你可以像这样使用这个组件:

import Tabs from "./MyTabs";

const tabs = [
  {
    label: "Tab 1",
    Component: <div>Hello, I am tab 1</div>
  },
  {
    label: "Tab 2",
    Component: <div>Hello, I am tab 2</div>
  },
  {
    label: "Tab 3",
    Component: (
      <div>
        <h1>Tab with heading</h1>
        <p>Hello I am a tab with a heading</p>
      </div>
    )
  }
];

export default function App() {
  return (
    <div>
      <Tabs tabs={tabs} />
    </div>
  );
}

这是带有完整示例的 Codesandbox


推荐阅读