如何在React Typescript中将路线链接添加到物料ui选项卡

问题描述

我在反应中使用ts。如何将路线链接添加到我的代码中的标签上

import React from 'react';
import { makeStyles,Theme } 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';

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

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

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

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

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

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

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

  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>
      <TabPanel value={value} index={0}>
        Item One
      </TabPanel>
      <TabPanel value={value} index={1}>
        Item Two
      </TabPanel>
      <TabPanel value={value} index={2}>
        Item Three
      </TabPanel>
    </div>
  );
}

我想创建/ home / item1,/ home / item2等链接。

如何在react打字稿中添加此内容。在标签上导航应更新浏览器地址栏上的网址。 或者,如果用户直接点击/ home / item2,则默认情况下应打开该标签页

解决方法

您可以使用Tab道具将Link设置为component渲染,如下所示:

import { Link } from 'react-router-dom'

...

<Tab
  ...
  component={Link}
  to="/home/item1"
/>

请注意,它还会通过任何其他非Tab道具传递到component,因此您可以指定to的{​​{1}}道具或任何其他需要设置的道具。>

要设置路线中的选定标签,请从位置中找到适当的索引(您可以从Link获得该索引),然后使用该索引初始化useLocation状态,而不是硬编码为{{ 1}}:

value

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...