【问题标题】:Display selected tab item into url path将选定的选项卡项显示到 url 路径中
【发布时间】:2021-12-28 22:48:08
【问题描述】:

我想在 url 路径中显示选定的选项卡项。我找到了这个 Material UI 示例:

import * as React from 'react';
import Tabs from '@mui/material/Tabs';
import Tab from '@mui/material/Tab';
import Typography from '@mui/material/Typography';
import Box from '@mui/material/Box';

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

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

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

function a11yProps(index: number) {
  return {
    id: `vertical-tab-${index}`,
    'aria-controls': `vertical-tabpanel-${index}`,
  };
}

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

  const handleChange = (event: React.SyntheticEvent, newValue: number) => {
    setValue(newValue);
  };

  return (
    <Box
      sx={{ flexGrow: 1, bgcolor: 'background.paper', display: 'flex', height: 224 }}
    >
      <Tabs
        orientation="vertical"
        variant="scrollable"
        value={value}
        onChange={handleChange}
        aria-label="Vertical tabs example"
        sx={{ borderRight: 1, borderColor: 'divider' }}
      >
        <Tab label="Item One" {...a11yProps(0)} />
        <Tab label="Item Two" {...a11yProps(1)} />
        <Tab label="Item Three" {...a11yProps(2)} />
        <Tab label="Item Four" {...a11yProps(3)} />
        <Tab label="Item Five" {...a11yProps(4)} />
        <Tab label="Item Six" {...a11yProps(5)} />
        <Tab label="Item Seven" {...a11yProps(6)} />
      </Tabs>
      <TabPanel value={value} index={0}>
        Item One
      </TabPanel>
      <TabPanel value={value} index={1}>
        Item Two
      </TabPanel>
      <TabPanel value={value} index={2}>
        Item Three
      </TabPanel>
      <TabPanel value={value} index={3}>
        Item Four
      </TabPanel>
      <TabPanel value={value} index={4}>
        Item Five
      </TabPanel>
      <TabPanel value={value} index={5}>
        Item Six
      </TabPanel>
      <TabPanel value={value} index={6}>
        Item Seven
      </TabPanel>
    </Box>
  );
}

https://mui.com/components/tabs/#VerticalTabs.tsx

沙盒:https://codesandbox.io/s/verticaltabs-material-demo-forked-yyqhm

我发现这个代码示例如何添加 url 参数: https://v5.reactrouter.com/web/example/nesting

知道如何实现代码以将选定的选项卡显示到 url 链接中。示例:https://yyqhm.csb.app/&lt;selected_tab&gt;

【问题讨论】:

    标签: javascript reactjs material-ui


    【解决方案1】:

    主要解决方案

    签出this solution

    它利用了react-router-dom,所以用BrowserRouter包装你的根组件

    ReactDOM.render(
      <StyledEngineProvider injectFirst>
        <BrowserRouter>
          <Demo />
        </BrowserRouter>
      </StyledEngineProvider>,
      document.querySelector("#root")
    );
    

    这是更新后的代码 - 基本思想是使用路径名作为要检查的值,并在选择选项卡时更新它:

    import { Routes, Route, useNavigate } from "react-router-dom";
    
    export default function VerticalTabs() {
      const [value, setValue] = React.useState(0);
      const navigate = useNavigate();
    
      const handleChange = (event: React.SyntheticEvent, newValue: number) => {
        navigate(newValue);
        setValue(newValue);
      };
    
      return (
        <Box
          sx={{
            flexGrow: 1,
            bgcolor: "background.paper",
            display: "flex",
            height: 224
          }}
        >
          <Tabs
            orientation="vertical"
            variant="scrollable"
            onChange={handleChange}
            value={
              window.location.pathname == "/"
                ? "/item_one"
                : window.location.pathname
            }
            aria-label="Vertical tabs example"
            sx={{ borderRight: 1, borderColor: "divider" }}
          >
            <Tab value="/item_one" label="Item One" {...a11yProps(0)} />
            <Tab value="/item_two" label="Item Two" {...a11yProps(1)} />
            <Tab value="/item_three" label="Item Three" {...a11yProps(2)} />
          </Tabs>
    
          <Routes>
            <Route
              path="/"
              element={
                <TabPanel value={value} index={0}>
                  Item One
                </TabPanel>
              }
            />
            <Route
              path="/item_one"
              element={
                <TabPanel value={value} index={0}>
                  Item One
                </TabPanel>
              }
            />
            <Route
              path="/item_two"
              element={
                <TabPanel value={value} index={1}>
                  Item Two
                </TabPanel>
              }
            />
            <Route
              path="/item_three"
              element={
                <TabPanel value={value} index={2}>
                  Item Three
                </TabPanel>
              }
            />
          </Routes>
        </Box>
      );
    }
    

    另类

    这是the code工作版本的链接。

    下面的代码读取当前页面的路径名,然后将其设置为state

    ...
      React.useEffect(() => {
        setValue( +window.location.pathname.substring(1) );
      }, []);
    

    您还可以定义一个字典,该字典用作一种倒排索引,以将自定义路径名与其相关索引值匹配,或者可能是一个打字稿枚举。

    {
      'item-one': 1,
      'item-two': 2,
      'item-three': 3,
      1: 'item-one',
      2: 'item-two',
      3: 'item-three'
    }
    

    Whenever a tab is selected, you can set the index to the path by manipulating history.

      const handleChange = (event: React.SyntheticEvent, newValue: number) => {
        window.history.replaceState({}, "", "/" + newValue);
        setValue(newValue);
      };
    ...
    

    【讨论】:

      猜你喜欢
      • 2020-06-06
      • 2021-01-22
      • 2017-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-25
      • 1970-01-01
      相关资源
      最近更新 更多