首页 > 解决方案 > 如何禁用 Material UI Link API 组件

问题描述

我之前使用的是 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>

标签: javascriptcssreactjsmaterial-ui

解决方案


Material-UI默认Link呈现为一个<a>元素。如果您希望它呈现为 a <button>(当您指定onClick而不指定时这将是合适的href),那么您需要指定component="button". 完成此操作后,disabled道具将按预期工作,但需要注意的是 Material-UILink没有任何样式用于“禁用”外观;因此,如果您希望链接在禁用时看起来有所不同,则需要自定义该状态的样式。

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

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>
  );
}

编辑禁用的链接/按钮


推荐阅读