javascript - 如何禁用 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>
解决方案
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>
);
}
推荐阅读
- java - 使用图像阅读器 getResourceAsStream 的图像未被读取
- c# - 如何在 C# 中从另一个列表中删除列表
- python - 在单元测试中创建 API 资源的最佳实践 - 数据库或 POST 端点?
- html - 表格中两行之间有间隙
- r - 使用 if-else 将输出保存在多个 for 循环中
- python - 访问存储在列表中的对象
- java - 是否有任何支持 Java 的 CentOS 7 OpenCV 构建?
- r - 如何在 R 中获得组合向量?
- python - Tkinter 网格:将当前行上的新列用于新小部件
- webgl - WebGL:为什么将透明源颜色与不透明目标颜色混合永远不会变成原始源颜色?