reactjs - 如何制作可重用的材质 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>
</>
)
}
解决方案
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>
);
}
推荐阅读
- react-native - 将信息发送到 React-native 上的选项卡
- python - 库安装 Python + Spyder
- json - 使用 Serde 反序列化跳过序列中的无效元素
- python-3.x - UnicodeDecodeError:“utf-16-le”编解码器无法解码位置 138-139 中的字节:非法编码
- angular - Angular 9 路由器同时连接到 2 个插座
- java - 对象工具不是包 scala 的成员
- c++ - 使用虚函数作为主题订阅者的回调
- angular8 - 子目录中的 Angular 8 路由器
- c++ - 将 lambda 作为模板参数传递?(c++20,未评估上下文中的 lambdas)
- java - java中的数组变量