【问题标题】:How to disable the Material UI Link API component如何禁用 Material UI Link API 组件
【发布时间】:2021-07-28 22:59:36
【问题描述】:

我之前使用的是 Material UI 的 Button 组件,它具有 disable 属性。基本上,该道具允许基于布尔值禁用按钮。因此,如果为真,则它被禁用。但是,现在我想切换到 Material UI Link 组件,它也是一个按钮,但它看起来像一个文本。它与按钮的作用相同,但看起来像一个链接。但是,它没有 disable 属性,或者似乎是因为我不认为它是 Material UI 文档中可能的属性。有什么解决办法吗?

*注意 - 这不是来自 React Router Dom 库。我正在为 React 使用 Material UI Library 中的链接。只是为了避免混淆。

<Link
  hover
  underline="hover"
  variant="body2"
  onClick={
    this.buyAll
  }>
Buy All Products
</Link>

【问题讨论】:

  • 这能回答你的问题吗? Easier way to to disable link in React?
  • @beskgar 感谢您的努力,但它没有回答我的问题。他们在那篇文章中引用的链接来自 React Router Dom 库。我所指的链接来自 Material UI Library
  • @kenny229 这里的Link 组件并不重要,它仍然有效。尝试链接帖子中的想法。

标签: javascript css reactjs material-ui


【解决方案1】:

Material-UI 的 Link 呈现为 &lt;a&gt; element by default。如果您希望它呈现为&lt;button&gt;(这在您指定onClick 而未指定href 时是合适的),那么您需要指定component="button"。完成此操作后,disabled 属性将按预期工作,但需要注意的是 Material-UI 的 Link 没有任何“禁用”外观样式;因此,如果您希望链接在禁用时看起来有所不同,则需要为该状态自定义样式。

下面是一个工作示例,包括一些示例禁用样式:

import React from "react";
import { makeStyles, withStyles } from "@material-ui/core/styles";
import MuiLink from "@material-ui/core/Link";
import Typography from "@material-ui/core/Typography";

const useStyles = makeStyles((theme) => ({
  root: {
    "& > * + *": {
      marginLeft: theme.spacing(2)
    }
  }
}));

const Link = withStyles({
  root: {
    "&[disabled]": {
      color: "grey",
      cursor: "default",
      "&:hover": {
        textDecoration: "none"
      }
    }
  }
})(MuiLink);

export default function Links() {
  const classes = useStyles();

  return (
    <Typography className={classes.root}>
      <Link component="button" onClick={() => console.log("hello")}>
        Link
      </Link>
      <Link
        component="button"
        disabled
        onClick={() =>
          console.log(
            "I'm disabled so this doesn't appear in the console when this is clicked."
          )
        }
      >
        Disabled Link
      </Link>
    </Typography>
  );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 2016-10-17
    • 2016-11-06
    • 2021-02-21
    • 2018-09-25
    • 2017-03-15
    相关资源
    最近更新 更多