ReactJS Material UI在按钮点击时禁用其他选项卡



为每个选项卡中的Button组件设置类似的操作代码

https://codesandbox.io/embed/cbn97?codemirror = 1

如何禁用当前选项卡上的按钮单击其他选项卡?

如何传递"disabled"属性转换为已显示、已呈现的选项卡组件,是否更新它?

ReactJS新功能

既然您在评论中指出当前页面也可能被禁用,我建议您这样做:

export default function SimpleTabs() {
  const classes = useStyles();
  const [value, setValue] = React.useState(0);
  const [isLoading, setIsLoading] = React.useState(false)
  const handleOperation = () => {
    setIsLoading(true)
    // Do some synchronous operation that takes time
    setIsLoading(false)
  }
  
  const handleChange = (event, 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)} disabled={isLoading}/>
          <Tab label="Item Two" {...a11yProps(1)} disabled={isLoading}/>
          <Tab label="Item Three" {...a11yProps(2)} disabled={isLoading}/>
        </Tabs>
      </AppBar>
      <TabPanel value={value} index={0}>
        <button onClick={handleOperation}>start operation</button>
      </TabPanel>
      <TabPanel value={value} index={1}>
        Item Two
      </TabPanel>
      <TabPanel value={value} index={2}>
        Item Three
      </TabPanel>
    </div>
  );
}

因此,上面的方法是创建一个isLoading状态,该状态标识一个选项卡按钮操作是否正在进行中。在选项卡按钮处理程序函数中,设置isLoadingtrue,使选项卡禁用,并在操作完成后将isLoading设置为false

只需将带有条件的函数的结果放在选项卡的disabled prop中:

export default function SimpleTabs() {
  const classes = useStyles();
  const [value, setValue] = React.useState(0);
  const [operationDone, setOperationDone] = React.useState(false)
  const handleChange = (event, newValue) => {
    setValue(newValue);
  };
  
  const isDisabled = (tabIndex) => {
    if(operationDone) {
      return false;
    }
    else {
      if(value !== tabIndex) {
        return true;
      }
      return false;
    }
  }
  return (
    <div className={classes.root}>
      <AppBar position="static">
        <Tabs value={value} onChange={handleChange} aria-label="simple tabs example">
          <Tab label="Item One" disabled={isDisabled(0)} {...a11yProps(0)} />
          <Tab label="Item Two" disabled={isDisabled(1)} {...a11yProps(1)} />
          <Tab label="Item Three" disabled={isDisabled(2)} {...a11yProps(2)} />
        </Tabs>
      </AppBar>
      <TabPanel value={value} index={0}>
        <button onClick={() => setOperationDone(true)}>change operation done</button>
      </TabPanel>
      <TabPanel value={value} index={1}>
        Item Two
      </TabPanel>
      <TabPanel value={value} index={2}>
        Item Three
      </TabPanel>
    </div>
  );
}

最新更新