简体   繁体   English

React.js Material-UI:以编程方式隐藏和显示选项卡

[英]React.js Material-UI: Programmatically hide and show tab

I am trying to show and hide the 2nd tab programmatically yet when I click on the 3rd tab I see the content of the 2nd tab.我正在尝试以编程方式显示和隐藏第二个选项卡,但是当我单击第三个选项卡时,我看到了第二个选项卡的内容。

Providing my code snippet and sandbox below在下面提供我的代码片段和沙箱

Can someone please help?有人可以帮忙吗?

https://codesandbox.io/s/material-demo-8je9d https://codesandbox.io/s/material-demo-8je9d

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

  useEffect((newValue) => {
    // const { user } = props;

    console.log("useEffect newValue--->", newValue);
  }, []);

  const handleChange = (event, newValue) => {
    console.log("newValue--->", newValue);
    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)} />
          {Tab2Visible === false ? (
            ""
          ) : (
            <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>
  );
}

If you do not provide any value property to the Tab component, MaterialUI defaults it to the index of the rendered items.如果您不向Tab组件提供任何 value 属性,MaterialUI 会将其默认为呈现项的索引。 Since only two Tab elements are rendered, the handleChange function gives value as 1 for Tab item 3.由于只呈现了两个 Tab 元素,handleChange function 将 Tab 项 3 的值设为 1。

Adding an explicit value property will work the way you want it to添加显式值属性将按照您希望的方式工作

 <Tabs
       value={value}
      onChange={handleChange}
      aria-label="simple tabs example"
    >
      <Tab label="Item One" value={0} {...a11yProps(0)} />
      {Tab2Visible === false ? (
        ""
      ) : (
        <Tab label="Item Two" value={1} {...a11yProps(1)} />
      )}
      <Tab label="Item Three" value={2} {...a11yProps(2)} />
    </Tabs>

Working DEMO 工作演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM