- React Material:UI Cookbook
- Adam Boduch
- 121字
- 2021-06-24 15:49:36
There's more...
Given that the active tab depends on the active route, you could completely remove any tab-related state. First, you create a TabContainer component to render the Tabs component:
const TabContainer = ({ value }) => (
<AppBar position="static">
<Tabs value={value}>
<Tab label="Item One" component={Link} to="/" />
<Tab label="Item Two" component={Link} to="/page2" />
<Tab label="Item Three" component={Link} to="/page3" />
</Tabs>
</AppBar>
);
Instead of supplying an onChange() handler to the Tabs component, the value property is passed from TabContainer. Now, you can render this component in each Route component, passing the appropriate value property:
const TabNavigationWithRoutes = withStyles(styles)(({ classes }) => (
<div className={classes.root}>
<Route
exact
path="/"
render={() => (
<Fragment>
<TabContainer value={0} />
<Typography component="div" className={classes.tabContent}>
Item One
</Typography>
</Fragment>
)}
/>
<Route
exact
path="/page2"
render={() => (
<Fragment>
<TabContainer value={1} />
<Typography component="div" className={classes.tabContent}>
Item Two
</Typography>
</Fragment>
)}
/>
<Route
exact
path="/page3"
render={() => (
<Fragment>
<TabContainer value={2} />
<Typography component="div" className={classes.tabContent}>
Item Three
</Typography>
</Fragment>
)}
/>
</div>
));
export default TabNavigationWithRoutes;
There's no more confusing the component state with the current Route and how the two interact. Everything is handled by the route.