1

Здравствуйте я новичок в frontend разработке. Хочу сделать панель навигации используя Tabs, чтобы при переходе на Tab срабатывал Link или NavLink для перехода по соответствующему Route.

пример стилизации Tab вкладок materialUi https://codesandbox.io/s/cvn6w

Я не до конца понял этот пример, что меня не устраивает в примере, я хотел отдельным компонентом Nav отрисовать Tabs с переходами по ссылкам Link, чтобы Route уже отработал.

import React, { Suspense, lazy } from "react";
import CssBaseline from "@material-ui/core/CssBaseline";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import "./App.css";
import Nav from "./components/Nav";

const DeviceOption = lazy(() =>  import("./components/deviceOptionComponents/DeviceOption"));
const About = lazy(() => import("./components/About"));

export default function App() {
  return (
    <div className="App">
      <CssBaseline />
      <Router>
        <React.Fragment>
          <Nav />
          <Suspense fallback={<div>Loading...</div>}>
            <Switch>
              <Route exact path="/" component={DeviceOption} />
              <Route path="/about" component={About} />
              <Route children={() => <h2>Not Found</h2>} />
            </Switch>
          </Suspense>
        </React.Fragment>
      </Router>
    </div>
  );
}

Панель навигации хочу отрисовать в компоненте Nav.

Подскажите пожалуйста как это сделать?

1 ответ 1

0

Решил вопрос через использование Redirect

import React from "react";
import PropTypes from "prop-types";
import { makeStyles } from "@material-ui/core/styles";
import AppBar from "@material-ui/core/AppBar";
import Tabs from "@material-ui/core/Tabs";
import Tab from "@material-ui/core/Tab";
import Typography from "@material-ui/core/Typography";
import Box from "@material-ui/core/Box";
import { Redirect } from "react-router-dom";

function TabPanel(props) {
  const { children, value, index, ...other } = props;

  return (
    <Typography
      component="div"
      role="tabpanel"
      hidden={value !== index}
      id={`simple-tabpanel-${index}`}
      aria-labelledby={`simple-tab-${index}`}
      {...other}
    >
      {value === index && <Box p={3}>{children}</Box>}
    </Typography>
  );
}

TabPanel.propTypes = {
  children: PropTypes.node,
  index: PropTypes.any.isRequired,
  value: PropTypes.any.isRequired
};

function a11yProps(index) {
  return {
    id: `simple-tab-${index}`,
    "aria-controls": `simple-tabpanel-${index}`
  };
}

const useStyles = makeStyles(theme => ({
  root: {
    flexGrow: 1,
    backgroundColor: theme.palette.background.paper
  }
}));

export default function Nav2() {
  const classes = useStyles();
  const [value, setValue] = React.useState(0);

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

  function RedirectRender(param) {
    switch (param) {
      case 0:
        return <Redirect to="/" />;
      case 1:
        return <Redirect to="/About" />;
      case 2:
        return <Redirect to="/NotFound" />;
      default:
        return <Redirect to="/About" />;
    }
  }

  return (
    <div className={classes.root}>
      <AppBar position="static">
        <Tabs
          value={value}
          onChange={handleChange}
          aria-label="simple tabs example"
        >
          <Tab label="Item One" {...a11yProps(0)} />
          <Tab label="Item Two" {...a11yProps(1)} />
          <Tab label="Item Three" {...a11yProps(2)} />
        </Tabs>
      </AppBar>
      {RedirectRender(value)}
    </div>
  );
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.